我有一個字符串C++字符串中的
「約翰」「你好提取兩個引號」
我期待引號提取到兩個字符串,這樣我可以將它們分類喜歡。
User: John
Text: Hello there
我想知道要做到這一點的最好辦法是什麼?有沒有一個字符串函數可以用來使這個過程簡單?
我有一個字符串C++字符串中的
「約翰」「你好提取兩個引號」
我期待引號提取到兩個字符串,這樣我可以將它們分類喜歡。
User: John
Text: Hello there
我想知道要做到這一點的最好辦法是什麼?有沒有一個字符串函數可以用來使這個過程簡單?
使用std::quoted
:http://en.cppreference.com/w/cpp/io/manip/quoted
#include <iomanip>
#include <sstream>
#include <iostream>
int main() {
std::string user, text;
std::istringstream iss("\"John\" \"Hello there\"");
if (iss >> std::quoted(user) >> std::quoted(text)) {
std::cout << "User: " << user << "\n";
std::cout << "Text: " << text << "\n";
}
}
注意它也支持轉義引號:如果輸入的是Me "This is a \"quoted\" word"
,將打印(也Live)
User: Me
Text: This is a "quoted" word
添加了現場演示 – sehe
這是一個使用一個可能的解決方案stringstream
:
std::string name = "\"Jhon\" \"Hello There\"";
std::stringstream ss{name};
std::string token;
getline(ss, token, '\"');
while (!ss.eof())
{
getline(ss, token, '\"');
ss.ignore(256, '\"');
std::cout << token << std::endl;
}
輸出:?最優雅的方式來分割字符串]
Jhon
Hello There
的可能的複製(https://stackoverflow.com/questions/236129/most-elegant-way-to-split-a-string) – user463035818
uhm,定義'easy'...這個問題有點模糊......有gazilion的做法,有gaziliion可能的要求... –