首页 > 解决方案 > 必须在 C++ 中将 c_str 用于 strchr 吗?

问题描述

我需要std::string在 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;

标签: c++

解决方案


代替使用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);

推荐阅读