我需要解析std::string in c++ std::string s = "my_prefix,my_body,my_suffix";
我只需要prefix, suffix。在C中(使用类似的char*作为输入),我会执行如下操作:
char *s = "my_prefix,my_body,my_suffix";
size_t N = strlen("my_prefix"); // This is actually a fixed length in my real case
char* suffix = 1 + strrchr(s, ',');
char* prefix[128];
snprintf(prefix, N+1, "%s", s);
printf("prefix = %s\n" "suffix = %s\n", prefix, suffix);我想在strchr中使用C++,但据我所见,实现只适用于char*。我必须在字符串上使用c_str(),还是有其他方法(例如,C++函数不boost之类的.我用的是非常瘦的C++)?
编辑:
这是我在C++上的尝试,这是一个很好的选择吗?
std::string s = "my_prefix,my_body,my_suffix";
char delimiter = ',';
std::string pre = s.substr(0, s.find_first_of(delimiter));
std::string suf = s.substr(1 + s.find_last_of (delimiter));
std::cout << pre << std::endl;
std::cout << suf << std::endl;发布于 2018-08-09 13:35:15
不使用strchr,您可以使用std::string::find_first_of/std::string::find_last_of和std::string::substr从s中获取前缀和后缀。
std::string s = "my_prefix,my_body,my_suffix";
std::string prefix = s.substr(0, s.find_first_of(","));
std::string suffix = s.substr(s.find_last_of(",") + 1);发布于 2018-08-09 13:36:31
首先,即使在C中,用strchr解析令牌化字符串也不是什么好事。strtok函数族提供了一个更好的选择。
在C++世界中,有几种实现C++惯用令牌解析的选项。对我来说,纯粹的标准方式似乎是将std::getline与std::stringstream结合使用。
示例:
std::istringstream str("This is my,rifle,this is my gun");
std::string token;
while (std::getline(str, token, ',')) {
// work with next token
}此外,Boost还提供了标记化解决方案: Boost.Split和Boost.Tokenizer,它们比getline支持的解析更具灵活性和功能丰富。
发布于 2018-08-09 13:37:19
C++的等效值可以是:
#include <string>
#include <iostream>
int main() {
std::string s = "my_prefix,my_body,my_suffix";
std::string::size_type i = s.find(',');
std::string::size_type j = s.rfind(',');
std::cout << "Prefix:" << s.substr(0, i) << std::endl;
std::cout << "Body:" << s.substr(i + 1, j) << std::endl;
std::cout << "Suffix:" << s.substr(j + 1) << std::endl;
}https://stackoverflow.com/questions/51768231
复制相似问题