Trimming a string after space

Nov 23, 2012 at 9:41am
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!
Nov 23, 2012 at 9:47am
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)
Nov 23, 2012 at 1:10pm
yes, '\0' needs to be inserted when the first space character is found.
Nov 23, 2012 at 2:01pm
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
Nov 23, 2012 at 2:29pm
@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 Nov 23, 2012 at 2:48pm
Nov 23, 2012 at 2:37pm
@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 Nov 23, 2012 at 2:38pm
Topic archived. No new replies allowed.