Question

I need to split the string on . in C++..

Below is my string -

@event.hello.dc1

Now I need to split on . on the above string and retrieve the @event from it and then pass @event to the below method -

bool upsert(const char* key);

Below is the code I have got so far after reading it from here -

void splitString() {

    string sentence = "@event.hello.dc1";

    istringstream iss(sentence);
    copy(istream_iterator<string>(iss), istream_iterator<string>(), ostream_iterator<string>(cout, "\n"));
}

But I am not able to understand how to extract @event by splitting on . using the above method as the above method only works for whitespace... And also how to extract everything from that string by splitting on . as mentioned like below -

split1 = @event
split2 = hello
split3 = dc1

Thanks for the help..

Était-ce utile?

La solution

You can use std::getline:

string sentence = "@event.hello.dc1";
istringstream iss(sentence);
std::vector<std::string> tokens;
std::string token;
while (std::getline(iss, token, '.')) {
    if (!token.empty())
        tokens.push_back(token);
}

which results in:

tokens[0] == "@event"
tokens[1] == "hello"
tokens[2] == "dc1"

Autres conseils

First off, you can change what is considered to be a space for a stream. The approach to do is to replace the std::ctype<char> facet in a new std::locale and then imbue() this newly created std::locale into the stream. However, the approach is a bit involved the the task at hand. In fact, to extract the first component of the string separated by a . I wouldn't even create a stream:

std::string first_component(std::string const& value) {
    std::string::size_type pos = value.find('.');
    return pos == value.npos? value: value.substr(0, pos);
}

Create a ctype facet something like this:

#include <locale>
#include <vector>

struct dot_reader: std::ctype<char> {
    dot_reader(): std::ctype<char>(get_table()) {}
    static std::ctype_base::mask const* get_table() {
        static std::vector<std::ctype_base::mask> rc(table_size, std::ctype_base::mask());

        rc['.'] = std::ctype_base::space;
        rc['\n'] = std::ctype_base::space; // probably still want \n as a separator?
        return &rc[0];
    }
};

Then imbue your stream with an instance of it, and read strings:

istringstream iss(sentence);

iss.imbue(locale(locale(), new dot_reader())); // Added this

copy(istream_iterator<string>(iss), 
     istream_iterator<string>(), 
     ostream_iterator<string>(cout, "\n"));

You can use the strtok function : http://en.cppreference.com/w/cpp/string/byte/strtok You can use by doing something like this :

 strtok(sentence.c_str(), ".");
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top