Trimming a string after space

Hey all!
I need some quick help. I need to trim all the remaining characters of a string after a space is found.

basically something like this: if s = "how are you doing?" that there would only be "How" left.

i tried doing this:

1
2
3
4
5
6
7
            int x =0;
            while(s[x] != ' '){
                       
                       s1[x] = s[x];
                       x++;
                       cout << s1;    
                       } 


but it doesnt work. Please help!
You need to append '\0' when the while loop is done. You also should cout after the loop is done (and after you append that 0)
yes, '\0' needs to be inserted when the first space character is found.
If that is an actual string (not an array of char), you can erase:

1
2
3
4
5
6
7
8
#include <iostream>
#include <string>
int main ()
{
    std::string s = "how are you doing?";
    s.erase(s.find(' '));
    std::cout << s << '\n';
}

demo: http://ideone.com/fZGunL
@Cubbi
If that is an actual string (not an array of char), you can erase:


And if that is an actual character array ( not a string) you can truncate the actual array size

1
2
3
4
5
char s[] = "how are you doing?";

if ( char *p = strchr( s, ' ' ) ) *p = '\0';

std::cout << s << std::endl;

Last edited on
@award982
if s = "how are you doing?" that there would only be "How" left.


By the way if to follow literally your description then the task is impossible because in the original string there is no such a word as How:)
Last edited on
Topic archived. No new replies allowed.