c++ - 如何提取字符串中的特定值

标签 c++ string delimiter

我需要从文件输入中提取存储的字符串中的特定值。它有多个定界符,我无法弄清楚如何从中提取每个特定值。

#include <vector>
#include <string>
#include <sstream>
#include <iostream>    
#include <fstream> 
using namespace std;


string ss = "[4, 90]-3-name";
// i need to extract the values 4, 90, 3 and name 
// the numbers can have multiple digits

stringstream tr(ss);
vector<string> result;

while( tr.good() )
{
    string substr;
    getline( ss, substr, '-' );
    result.push_back( substr );

}

for (int i = 0; i< result.size();i++)
    cout << result[i]<< endl;

output:
[4, 90]
3
name

最佳答案

如果您知道所有可能的定界符,那么您可以将 ss 中的每个定界符替换为连字符,然后上面的代码就可以工作了。请参阅替换功能上的链接 http://www.cplusplus.com/reference/string/string/replace/

关于c++ - 如何提取字符串中的特定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57230569/

相关文章:

excel - 如何仅使用空格而不使用句点作为分隔符来拆分单元格

mysql - MySql 中的分隔符错误

java - 将 strings.xml 中的字符串放入 Toast 消息中

c++ - cmath 重载函数 C++ 的问题

c++ - 为什么右值不能用于初始化左值引用?

c++ - 定义最大 double 时,“无法在初始化中将 'double (*)() noexcept' 转换为 'double'”

java - 填写 "secret word"字母

c++ - 将 unicode(带 BOM)字符串转换为 ASCII std::string

c# - 分隔符分隔的字符串到 TreeView C#

c++ - 停止主线程的无限循环