Click here to Skip to main content
15,882,055 members
Please Sign up or sign in to vote.
2.00/5 (2 votes)
See more:
how to split the first word form the string in C++

Eg. This is a test string.
It is an example sentence.

I only want the result as

This
It
Posted
Updated 15-Nov-10 2:08am
v2

well it's pretty simple.

let's store the string in an array:

C#
char str[20]="This is a test string";


and store the result in some other array:

C#
char result[10];


then use a for loop to detect when does the first "space" comes. The string of characters which comes before the first space will be the first word.

C#
for(i=0;str[i]!=" ";i++)
{
 result[i]=str[i];
}


the for loop exits when the condition str[i]!=" " becomes false.
so your result is stored in result.

Hope you understood how it worked which is more important!
 
Share this answer
 
v3
Comments
Alain Rist 15-Nov-10 11:47am    
At least change string to char in your arrays, as is it does not compile and is very confusing
Tarun.K.S 15-Nov-10 23:57pm    
Updated. There is nothing complex to be confused.
Alain Rist 16-Nov-10 2:46am    
No more confusion between 'char' and 'string', better indeed :)
Try something as follows:

C#
string str = "This is a test string";

int i = str.find_first_of(' ');

string res(str.begin(), str.begin() + i);
 
Share this answer
 
Comments
Tarun.K.S 15-Nov-10 8:45am    
i don't think this is possible in C++.
KingsGambit 15-Nov-10 9:09am    
It is pure C++. Need to include std library header for string.
not sure what the C++ syntax is, but in most languages you would split the line on the space and take the first element from the resultant array.
 
Share this answer
 
hi
Have a look Here[^]

Change language tab to C++ & Copy code snippet, Change delimiter(Only space is required). Access first word from array ( i think that you want. )
 
Share this answer
 
Comments
Tarun.K.S 15-Nov-10 9:19am    
Eswa, the link says page not found.
Use the built-in facilities of the Standard C++ Library.
The first (blank separated) word of a std::string sentence is sentence.substr(0, sentence.find(' ')) for instance:
C++
#include <string>
std::string sentence = "It is an example sentence.";
std::string first_word = sentence.substr(0, sentence.find(' '));

cheers,
AR
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900