c++ - 必须在 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;
解决方案
代替使用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);
推荐阅读
- javascript - 如何在 jstree 复选框中获取阴影元素?
- nginx - Nginx 和 Cloudflare:err_too_many_redirects
- c# - C# DateTime 通过方法参数传递时始终为 01/01/0001
- matplotlib - 设置 figtext 的范围
- node.js - 如何使用套接字将请求代理到 h2c HTTP/2 服务器?
- android - Recyclerview 未显示在片段中
- php - 动态创建 Laravel 模型
- r - 3 维数据框的预测建模
- javascript - 通过文本输入实时更新 javascript 变量
- python - 是否可以使用 python 从已发布的 Tableau 工作簿/服务器中提取数据