4

我需要.在 C++ 中拆分字符串..

下面是我的字符串 -

@event.hello.dc1

现在我需要拆分.上面的字符串并从中检索@event,然后传递@event给下面的方法 -

bool upsert(const char* key);

以下是我从这里阅读后得到的代码-

void splitString() {

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

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

但我无法理解如何@event通过使用上述方法拆分来提取,.因为上述方法仅适用于空格......以及如何通过拆分从该字符串中提取所有内容,.如下所述 -

split1 = @event
split2 = hello
split3 = dc1

谢谢您的帮助..

4

4 回答 4

12

您可以使用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);
}

这导致:

tokens[0] == "@event"
tokens[1] == "hello"
tokens[2] == "dc1"
于 2013-10-14T22:11:14.070 回答
1

首先,您可以更改被认为是流空间的内容。要做的方法是std::ctype<char>在一个新的方面替换这个切面,std::locale然后将imbue()这个新创建std::locale的放入流中。但是,该方法有点涉及手头的任务。事实上,要提取由 a 分隔的字符串的第一个组件,.我什至不会创建流​​:

std::string first_component(std::string const& value) {
    std::string::size_type pos = value.find('.');
    return pos == value.npos? value: value.substr(0, pos);
}
于 2013-10-14T22:13:37.953 回答
1

创建一个像这样的 ctype facet:

#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];
    }
};

然后用它的实例灌输你的流,并读取字符串:

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"));
于 2013-10-14T22:14:03.963 回答
-3

您可以使用 strtok 函数:http ://en.cppreference.com/w/cpp/string/byte/strtok 您可以通过执行以下操作来使用:

 strtok(sentence.c_str(), ".");
于 2013-10-14T22:12:14.867 回答