Split up text with mulitple delimiters

William Hemsworth 0 Tallied Votes 267 Views Share

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 ( " ,!" )

#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

i believe there are better ways for doing it! such as using strtok()! for example.!

William Hemsworth 1,339 Posting Virtuoso

Perhaps read the description, it may not be the best way of doing it, but this is explaining how you can manually achive it, to understand how it works.

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.