如何在C++中解析包含空格的字符串
How to parse a string containing spaces in C++?
我有一个这样的字符串:
aaa bbb
字符串的第二部分前面有一个空格。我的目标是只解析第一部分,所以aaa
。空间用完后的一切。我如何在C++中做到这一点?
std::string s = "aaa bbb";
std::string s_before_space = s.substr(0, s.find(' '));
std::string s = "aaa bbb";
s = s.substr(0, s.find_first_of(' '));
std::string s = "aaa bbb";
std::istringstream ss(s);
std::string token;
if (ss>>token) // or: while(ss>>token) for _all_ tokens
{
std::cout << "first token only: " << token << std::endl;
}
或者,使用容器并使用<algorithm>
std::string s = "aaa bbb";
std::istringstream ss(s);
std::vector<std::string> elements;
std::copy(std::istream_iterator<std::string>(ss),
std::istream_iterator<std::string>(),
std::back_inserter(elements));
// elements now contains the whitespace delimited tokens
包括:
#include <sstream> // for ostringstream/istringstream/stringstream
#include <algorithm> // for copy
#include <iterator> // for istream_iterator/back_inserter
用户关注的tokenizer,取自本网站上的一些早期帖子。
void Tokenize(const std::string& str, std::vector<std::string>& tokens,const std::string& delimiters = " ") {
std::string::size_type lastPos = str.find_first_not_of(delimiters, 0);
std::string::size_type pos = str.find_first_of(delimiters, lastPos);
while (std::string::npos != pos || std::string::npos != lastPos){
tokens.push_back(str.substr(lastPos, pos - lastPos));
lastPos = str.find_first_not_of(delimiters, pos);
pos = str.find_first_of(delimiters, lastPos);
}
}
相关文章:
- 如何在c++中使用system()来运行包含空格的python脚本
- 如何处理包含空格的 cin 的用户输入?
- 如何在C++的凯撒密码程序中包含空格?
- C++ 逐行从文件(包含空格)读取数据
- 使用分隔符空格解析字符串,但字符串也包含空格
- C++:按制表符拆分字符串,但包含空格
- 崇高文本 3 - 在终端中编译并运行 C++ 程序(路径包含空格)
- 如何接受字符串中包含空格的字符串向量
- 如何 ROT 加密包含空格的字符串?
- 读取可能包含空格的字符串
- 如何将字符串与包含空格的短语一起使用
- 无法获取包含C++空格的输入
- 为什么这个 leveldb 代码会截断包含空格的"std::string"?
- 修改 gettext .pot 文件输出以排除空字符串或仅包含空格的字符串
- 如何从包含空格的 stdin 输入字符串
- 如何在文件读取中包含空格
- 如何检查字符串是否包含空格/制表符/换行符(任何空白内容)?
- 如何将包含空格和数字的句子从大写转换为小写
- 如何使用 scanf 从用户输入中获取字符串 ( char * ),由双引号分隔并包含空格
- 如何以包含空格的字符串形式获取输入