First word of sentence (by creating another null terminated string) – CSKC
Sign In

Search

Solved Problem #CPP#2601    siteicon   siteicon  

Problem Statement - First word of sentence (by creating another null terminated string)

Write a program to print the first word of a sentence given by the user by creating another null terminated string.

Program Approach

  • A separate character array for collecting the characters of first word is declared.
  • In this loop one looks for a matching space(‘ ‘) character. Until it is found character by character copying is done to the target array.
  • In the end the null character is placed where the space was found to make it a proper null terminated string.

Solution

TC++ #2601

 

×

Ask AI About This Code

Default Prompt that is passed along with the code is given below, You can write your own prompt if you so desire.



×

Test CPP

Alternate (?) :

char str[80]; cout<<“Input a small sentence:” ; cin.getline(str,80);
User given sentence is collected in str.

for(int i=0;str[i]!=’ ‘;i++) { fword[i]=str[i];spaceAt++;}
The loop runs from first index position to the place where first space in the sentence occurs. In each iteration it keeps copying 1 character from source array str to target array fword. It also increments a variable called spaceAt in every iteration. When the loop ends this spaceAt variable will contain the index of character array where space is found.

fword[spaceAt]=”;
After the loop we place the null character exactly at the location where first space was there so that the array becomes a proper null terminated string.

cout<<fword<<endl; //The well defined string is now printed

 

Notes

  • This code can also be done by using the index variable i itself provided it is defined above the for loop scope.


Suggested Filename(s): firstwrd.cpp



Share

Created: 13-Jan-2018 18:12 | Updated: 13-Jan-2018 18:23|