This snippet shows how you can manually split up a sentence using multiple delimiters. In this example, I split up this sentence: "Hello, my name is william!"
into the following: "Hello"
"my"
"name"
"is"
"william"
As you can see, the delimiters are not included ( " ,!"
)
Split up text with mulitple delimiters
#include <iostream>
#include <vector>
#include <string>
using namespace std;
// Returns true if text contains ch
inline bool TextContains(char *text, char ch) {
while ( *text ) {
if ( *text++ == ch )
return true;
}
return false;
}
void Split(char *text, char *delims, vector<string> &words) {
int beg;
for (int i = 0; text[i]; ++i) {
// While the current char is a delimiter, inc i
while ( text[i] && TextContains(delims, text[i]) )
++i;
// Beginning of word
beg = i;
// Continue until end of word is reached
while ( text[i] && !TextContains(delims, text[i]) )
++i;
// Add word to vector
words.push_back( string(&text[beg], &text[i]) );
}
}
int main() {
vector<string> words;
// Split up words
Split( "Hello, my name is william!", " ,!", words );
// Display each word on a new line
for (size_t i = 0; i < words.size(); ++i)
cout << words[i] << '\n';
cin.ignore();
}
William Hemsworth 1,339 Posting Virtuoso
Master. 0 Newbie Poster
William Hemsworth 1,339 Posting Virtuoso
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.