0

Possible Duplicate:
Splitting a string in C++

I'm trying to split a single string object with a delimeter into separate strings and then output individual strings.

e.g The input string is firstname,lastname-age-occupation-telephone

The '-' character is the delimeter and I need to output them separately using the string class functions only.

What would be the best way to do this? I'm having a hard time understanding .find . substr and similar functions.

Thanks!

Community
  • 1
  • 1
Tex Qas
  • 371
  • 1
  • 3
  • 4
  • You can look through the answers in here: http://stackoverflow.com/questions/236129/splitting-a-string-in-c – chris Oct 28 '12 at 20:46
  • What is it that you don't understand about the functions? If we know that, it's a lot easier to explain what you don't understand. – chris Oct 28 '12 at 20:51

2 Answers2

2

I think string streams and getline make for easy-to-read code:

#include <string>
#include <sstream>
#include <iostream>

std::string s = "firstname,lastname-age-occupation-telephone";

std::istringstream iss(s);

for (std::string item; std::getline(iss, item, '-'); )
{
    std::cout << "Found token: " << item << std::endl;
}

Here's using only string member functions:

for (std::string::size_type pos, cur = 0;
     (pos = s.find('-', cur)) != s.npos || cur != s.npos; cur = pos)
{
    std::cout << "Found token: " << s.substr(cur, pos - cur) << std::endl;

    if (pos != s.npos) ++pos;  // gobble up the delimiter
}
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
0

I'd do something like this

do
{        
    std::string::size_type posEnd = myString.find(delim);
    //your first token is [0, posEnd). Do whatever you want with it.
    //e.g. if you want to get it as a string, use
    //myString.substr(0, posEnd - pos);
    myString = substr(posEnd);
}while(posEnd != std::string::npos);
Armen Tsirunyan
  • 130,161
  • 59
  • 324
  • 434