tags:

views:

104

answers:

2

The program takes a string using getline, and then passes that string to a function where it stores the string into substrings separated by whitespace. I did that just by reading characters with a loop.

However, now I'm trying to pass a second string argument that separates the strings into substrings if the loop encounters characters in the 2nd string argument. This is what I have so far.

#include "std_lib_facilities.h"

vector<string> split(const string& s, const string& w) // w is second argument
{
    vector<string> words;
    string altered;
    for(int i = 0; i < s.length(); ++i)
    {
        altered+=s[i];
        if(i == (s.length()-1)) words.push_back(altered);
        else if(s[i] == ' ')
        {
            words.push_back(altered);
            altered = "";
        }
    }

    return words;
}



int main()
{
    vector<string> words;
    cout << "Enter words.\n";
    string word;
    getline(cin,word);
    words = split(word, "aeiou"); // this for example would make the letters a, e, i, o,
                                  // and u divide the string
    for(int i = 0; i < words.size(); ++i)
            cout << words[i];
    cout << endl;
    keep_window_open();
}

However, obviously I can't do something like

if(s[i] == w)

because s[i] is a char and w is a string. Do I need to use a stringstream to parse the string instead of the loop I implemented? I actually played around with stringstream, but don't really know how it could help because either way I have to read the characters 1 by 1.

P.S. The arguments to split must be passed as strings, and the input form in main() must be a getline.

+6  A: 

Look at std::string::find_first_of. This allows you to easily ask a std::string object for the position of the next of any characters in another string object.

For example:

string foo = "This is foo";
cout << foo.find_first_of("aeiou"); // outputs 2, the index of the 'i' in 'This'
cout << foo.find_first_of("aeiou", 3); // outputs 5, the index of the 'i' in 'is'

Edit: whoops, wrong link

Tyler McHenry
Getting the no matching function for call error, and the string header is part of the facilities header. Weird.
trikker
Got it working.
trikker
Most of the find, swap, etc. type functions are located under <algorithm>.
Hooked
That's true of the standalone functions, but there is a find_first_of that is a member function of std::string.
Tyler McHenry
A: 

You can use strtok for this purpose. It is already implemented in STL libraries.

#include 
#include 

int main ()
{
  char str[] ="- This, a sample string.";
  char * pch;
  printf ("Splitting string \"%s\" into tokens:\n",str);
  pch = strtok (str," ,.-");
  while (pch != NULL)
  {
    printf ("%s\n",pch);
    pch = strtok (NULL, " ,.-");
  }
  return 0;
} 
Janaka