Click here to Skip to main content
15,662,842 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

Updated 15-Nov-10 2:08am

well it's pretty simple.

let's store the string in an array:

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

and store the result in some other array:

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.

for(i=0;str[i]!=" ";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
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:

string str = "This is a test string";

int i = str.find_first_of(' ');

string res(str.begin(), str.begin() + i);
Share this answer
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
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
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:
#include <string>
std::string sentence = "It is an example sentence.";
std::string first_word = sentence.substr(0, sentence.find(' '));

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