1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
| #include <iostream>
#include <string>
#include <list>
using namespace std;
void split(const string &in, list<string> &out)
{
// initialisation
out.clear();
unsigned int begin = 0;
unsigned int end = 0;
while (begin < in.size())
{
// on ignore les espaces du début
while (begin < in.size() && in[begin] == ' ')
{
++begin;
}
// on recherche l'espace suivant
end = begin + 1;
while (end< in.size() && in[end] != ' ')
{
++end;
}
// on récupère la sous-chaine
if (begin < in.size())
{
out.push_back(in.substr(begin, end-begin));
begin = end + 1;
}
}
}
void print(const list<string> &in)
{
list<string>::const_iterator it;
cout << "String list size: " << in.size() << endl;
for (it = in.begin(); it != in.end(); ++it)
{
cout << "- \"" << *it << "\"" << endl;
}
cout << endl;
}
int main(int argc, char *argv[])
{
string line1 = " configuration1 exemple";
string line2 = "configuration2 exemple2 exemple3 exemple4";
string line3 = "configuration3 exemple5";
list<string> liste;
split(line1, liste);
cout << "line: \"" << line1 << "\"" << endl;
print(liste);
split(line2, liste);
cout << "line: \"" << line2 << "\"" << endl;
print(liste);
split(line3, liste);
cout << "line: \"" << line3 << "\"" << endl;
print(liste);
} |