Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easiest way to separate a string by spaces?

Tags:

c++

string

It's been a long time since I've used C++, been using Javascript in my free time and now I'm not sure exactly what I remember.

Basically I just need to separate a string into parts by looking at the spaces.

All the links I've seen are homemade functions, but I could have sworn there was a way to do it using the standard library by using streams, but again, I'm having a tough time recalling it and my google results aren't helping either.

Keep in mind that it isn't a stream I am taking from, it's just a string like "Bob Accountant 65 retired" and I have to extract each item in the string to its own data field. I've been messing with ifstreams and ofstreams but I'm not even sure what I'm doing, having forgot the syntax for it.

like image 608
Turner Houghton Avatar asked Dec 21 '25 05:12

Turner Houghton


1 Answers

std::strtok is the C-style way to do it. You might be thinking of using a std::stringstream, e.g.:

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

int main() {
    std::string input = "foo bar baz  quxx\nducks";
    std::stringstream ss(input);

    std::string word;
    while (ss >> word) {
        std::cout << word << '\n';
    }
}

When run, that displays:

foo
bar
baz
quxx
ducks

If you want to read data from a std::stringstream (or any type of std::istream, really) into a specific data type, you can follow @JerryCoffin's excellent suggestion of overloading the stream operator>> for your data type:

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

struct Employee {
    std::string name;
    std::string title;
    int age;
    std::string status;
};

std::istream& operator>>(std::istream &is, Employee &e) {
    return is >> e.name >> e.title >> e.age >> e.status;
}

int main() {
    std::string input = "Bob Accountant 65 retired";
    std::stringstream ss(input);

    Employee e;
    ss >> e;

    std::cout << "Name: " << e.name
        << " Title: " << e.title
        << " Age: " << e.age
        << " Status: " << e.status
        << '\n';
}
like image 175
Nate Kohl Avatar answered Dec 23 '25 17:12

Nate Kohl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!