Is there any functions that split a string?

Such as this:

string s1 = "lol-lol2-lol3";
string s2[3];
char spliter_char = '-';

split_strings(s1, s2, spliter_char);
//s2 should now be:
//{"lol","lol2","lol3"}

Recommended Answers

All 5 Replies

You can use the substr() function to copy part of a string to another string.
I find this website really good for stuff like this here.
That is a link to the substr() reference but there is a whole lot of examples for other class functions.

Added an example program I made for an assignment that takes in a sentence and stores all the words into a vector. You can use this example and instead of looking for a space character look for the '-'.

Not tested.

bool split_string(string& src, string& dst, char splitter)
{ 
   //check for valid size or if splitter is in src
    if(src.size() == 0 || src.find(splitter) == string::npos)
        return false;
    int i = 0;
    while(src[i] != splitter)
           dst += src[i++];

  return true;
}

What i mean is to have to dst thing a char* array.

I want it to do this:

string str = "10-20-30";
char* buffer[3];
split_string(str, buffer, '-');
//buffer should now be {"10","20","30"}

Havn't tested this, so there might be a few errors:

void split_string(const string& src, vector<string>& dst, char split)
{
    int startPos = 0, endPos = src.find(split);
    while(endPos != string::npos)
    {
        dst.push_back(src.substr(startPos, endPos-startPos));
        startPos = endPos + 1;
        endPos = src.find(split, startPos);
    }
}

I posted the answer in my attachment and you ended up just reposting what you put up in your 1st post.

I took my code and deleted a whole bunch of stuff and changed the find character from ' ' to '-'. This stores everything to a vector but you can change it to a char* array[3] if you want to but I'll leave you to think that part up.

#include <iostream>
#include <string>
#include <vector>

using namespace std;

int main()
{
	string sentence, word, charString, wordString;
	vector<string>wordlist;
	
	cout << "Please enter some words (ctrl-d or ctrl-z to quit): " << endl;
	
	while(getline(cin, sentence))
	{
		wordlist.clear();
		int lastSpace = -1;
		
		for( int i = 0; i < sentence.length(); i++ )
		{
			if( sentence[i] == '-' )
			{
				word = sentence.substr(lastSpace+1, (i-lastSpace-1));
				wordlist.push_back(word);
				lastSpace = i;
			}
			else if( i == sentence.length()-1 )
			{
				word = sentence.substr(lastSpace+1, (i-lastSpace));
				wordlist.push_back(word);
			}
		}
		
		if( wordlist.size() > 0 )
		{
			for(int i = 0; i < wordlist.size(); i++)
			{
				cout << wordlist[i] << endl;
			}
		}
		else
		{
			cout << "You didn't enter any words." << endl << endl;
		}
		
	}
    system("PAUSE");
    return 0;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.