I'm kind of new to C++ and I want to turn a string into an array. I want to separate each element of the array by detecting the "+" signs in the string. I know there is a function that can do this, but I just can't remember what it is.
Printable View
I'm kind of new to C++ and I want to turn a string into an array. I want to separate each element of the array by detecting the "+" signs in the string. I know there is a function that can do this, but I just can't remember what it is.
I'm not sure if you are aware of this.. but <string> class variables can be accessed like arrays...
example:
Code:string first_name = "Jose";
char first_initial = first_name[0];
so basically, a string class variable are just an array of characters.
No, no, no. Let's say I have this string: "Joe+Dan+Tom"
I want to create an array with Joe Dan and Tom as the elements of it. I want to create an array from the string by separating the elements with the plus sign.
If you put that string into a stringstream, you can use the getline function with '+' as the delimiter.
strtok perhaps?
Quote:
#include <string.h>
char *strtok(char *s1, const char *s2);
Description:
Searches one string for tokens, which are separated by delimiters defined in a second string.
strtok considers the string s1 to consist of a sequence of zero or more text tokens, separated by spans of one or more characters from the separator string s2.
The first call to strtok returns a pointer to the first character of the first token in s1 and writes a null character into s1 immediately following the returned token. Subsequent calls with null for the first argument will work through the string s1 in this way, until no tokens remain.
The separator string, s2, can be different from call to call.
Note:
Calls to strtok cannot be nested with a function call that also uses strtok. Doing so will causes an endless loop.
Return Value:
strtok returns a pointer to the token found in s1. A NULL pointer is returned when there are no more tokens.
Umm...how would I do that? Heh, sorry, as I said, I'm pretty new to C++. I only know PHP, so I am basically thinking of a function like explode() in PHP. Is there a function like that in C++?
I'd stick to C++ strings, and use the "find" and "substr" methods which come with that class.
http://www.bgsu.edu/departments/comp...cs/string.html
That made no sense to me, can anyone else help?
Ok so you want to call explode() on a string and get back an array of strings right?
So you should want as a return from your explode function a vector<string>
You should pass your explode function a string or string & and a delimiter character.
Inside your explode function you'll have to call find to find the the occurances of the delimiter character. As you find them you simply call substr to pull out the piece you want and then push_back it into the vector. Once you are done parsing the string then you return the vector.