Splitting a C++ String

cyberphant0m

Member
Oct 21, 2003
99
0
0
I was reading an article, that said I'd be able to use the before() and after() methods on a string in order to split a string... I tried it using the ever popular "Hello world" string, but my program wont compile... Here's my code and my errors.

7 C:\programs\cardgame\cardgame.cpp
no matching function for call to ` std::basic_string<char, std::char_traits<char>, std::allocator<char> >::

8 C:\programs\cardgame\cardgame.cpp
no matching function for call to ` std::basic_string<char, std::char_traits<char>, std::allocator<char> >::

Im using Dev-C++ 4.9.8.7 on Windows XP... I've tried #include'ing the string library, but that leads to the same error messages
 

pilot006

Member
Mar 4, 2003
33
0
0
Well... this is how I'd edit your code. All I do is find the whitespace character, and then use substrings to print out what's before and after it. Should work.

I'm at work right now and don't have .NET handy... so lemme know if it gives you any grief.
 

cyberphant0m

Member
Oct 21, 2003
99
0
0
Thanx for your help guys...

I tweaked pilot006's code, because it was chopping off the "o" from hello, and also made it so it wouldn't include the space in the second string...
Also, on my compiler, I don't need to include the string header... wierd, but works out for me...:cool:
My code looks like this now (i thought i'd include it here in case someone stumbled onto this thread with the same question.
 

pilot006

Member
Mar 4, 2003
33
0
0
Doh! Everyone may swear at their compilers... but it woulda been nice to have one then. Glad you got it working. I used to hate substring, but it's a nice rub on the belly when it comes to string morphing. Happy coding!
 

BFG10K

Lifer
Aug 14, 2000
22,709
3,007
126
My goodness, those code tags rock. I tip my hat to the new version of the forum. :cool:

FYI - there's a standard C function called strtok which can split a string up based on token(s) you pass it. In the above example you'd simply pass it in a space for the token and it would return each word for you.
 

Barnaby W. Füi

Elite Member
Aug 14, 2001
12,343
0
0
Originally posted by: cyberphant0m
Also, on my compiler, I don't need to include the string header... wierd, but works out for me...:cool:

What works and what's correct are often not the same. If you use std::string, you should include <string>.