Daniel said:
Hello
I've got a string in a char* variable. This string is entered by the user
and it can contain some \n
Now I want to split the entered text by this char into different strings.
Exists there any function to do this? The function should return e.g a
char** in which each line is.
You may use std::find() to find each '\n' and split strings. Assuming a char * string:
#include <vector>
#include <string>
#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstddef>
std::vector<std::string> SplitString(const char * const cstring)
{
using namespace std;
const size_t SIZE= strlen(cstring);
vector<string> vec;
const char *current, *previous;
for(previous= current= cstring; current!= cstring+SIZE; )
{
current= find(previous, cstring+SIZE, '\n');
vec.push_back( string(previous, current) );
if(current!= cstring+SIZE)
previous= current+1;
}
return vec;
}
int main()
{
using namespace std;
const char *p= "Some\nTest\nString";
vector<string> vec= SplitString(p);
for(vector<string>::size_type i=0; i<vec.size(); ++i)
cout<<vec
<<"\n";
}
However this is tricky and error prone. By using a std::string in the first place, it
makes things easier:
#include <vector>
#include <string>
#include <algorithm>
#include <iostream>
std::vector<std::string> SplitString(const std::string &arg)
{
using namespace std;
string &s= const_cast<string &>(arg);
vector<string> vec;
string::iterator current, previous;
for(previous= current= s.begin(); current!= s.end(); )
{
current= find(previous, s.end(), '\n');
vec.push_back( string(previous, current) );
if(current!= s.end())
previous= current+1;
}
return vec;
}
int main()
{
using namespace std;
string s= "Some\nTest\nString";
vector<string> vec= SplitString(s);
for(vector<string>::size_type i=0; i<vec.size(); ++i)
cout<<vec<<"\n";
}
The above involves vector copying, and if this produces overhead, you may do:
#include <vector>
#include <string>
#include <algorithm>
#include <iostream>
void SplitString(std::vector<std::string> &vec, const std::string &arg)
{
using namespace std;
string &s= const_cast<string &>(arg);
string::iterator current, previous;
for(previous= current= s.begin(); current!= s.end(); )
{
current= find(previous, s.end(), '\n');
vec.push_back( string(previous, current) );
if(current!= s.end())
previous= current+1;
}
}
int main()
{
using namespace std;
string s= "Some\nTest\nString";
vector<string> vec;
SplitString(vec, s);
for(vector<string>::size_type i=0; i<vec.size(); ++i)
cout<<vec<<"\n";
}