从字符串c++中提取数字

extract numbers from string c++

本文关键字:提取 数字 c++ 字符串      更新时间:2023-10-16

我有一个字符串,看起来像这样:

foo
$RESULT :(0.2374742, 0.267722, ...up to a million more)
$STATES :{1, 3, 5, ...}
foo 

所以字符串中的某个地方是结果,紧接着是状态,我想把结果保存在一个列表中,把状态保存在另一个列表。

我想我需要一些类似"从$RESULT:("to")读取"的东西来获取每个数字并推送到列表,对于States也是如此,但我不知道如何读取从"a"到"b"的字符串并标记其内容。

您可以使用boost令牌化器:这是一个仅用于标头的库,使用非常方便

int index = s.find("RESULT: (");
int index2 = s.find("$STATE");
int length = index2 - index;
if (index != string::npos) {
    temp = s.substr(index + 7, length - 8);
}
typedef tokenizer<char_separator<char> > tokenizer;
char_separator<char> sep(",() ");
tokenizer tokens(temp, sep);
for (tokenizer::iterator tok_iter = tokens.begin();
        tok_iter != tokens.end(); ++tok_iter) {
    basic_string<char> tempValue = *tok_iter;
    values.push_back(tempValue);
}

C++中的标记化通常使用getline来完成,因此:getline(输入流,保存字符串的位置,分隔符字符);

尝试构建一个用于读取的类,将每一行保存到集合中,然后根据需要标记每一行,并在算法中发送到所需的集合。

您可以使用strtok()库函数-http://www.cplusplus.com/reference/clibrary/cstring/strtok.

找到"("的第一个acrance,然后是")"符号的第一个,并获得两个索引之间的子字符串(第一个是开始,长度是结束-开始),然后可以对第一个")"标记之后的子字符串执行同样的操作(对于状态)。

temp_str = input_str
do twice {
    start    = findChar(temp_str, '(');
    end      = findChar(temp_str, ')')
    len      = end - start + 1
    result   = substr(temp_str, start, len);  
    save_result_to_file(result)
    temp_str = substr(temp_str, end + 1);
}

不要记得确切的c++命令,但你肯定会有它们的。

#include <string>
#include <vector>
using namespace std;
int main()
{
  //This is your source string
  string Source = "foo $RESULT :(0.2374742, 0.267722) $STATES :{1, 3, 5} fo0";
  //Get the $RESULT section of the string, encapsulated by ( )
  string Results = Source .substr(Source .find("(") + 1, (Source .find(")") - Source .find("(")) - 1);
  //Get the $STATES section of the string, encapsulated by { }
  string States = Source .substr(Source .find("{") + 1, (Source .find("}") - Source .find("{")) - 1);
  vector<double> ResultsList;
  vector<int> StatesList;
  //While the Results string still has remaining ", " token/seperators in it
  while(Results.find(", ") != string::npos)  
  {
    //Get the next value and insert it into the vector (converting it from string to float using atof)
    ResultsList.push_back(atof(Results.substr(0, Results.find(", ")).c_str()));
    //Crop that off the oringal string
    Results = Results.substr(Results.find(", ") + 2);  
  }
  //Push the final value (no remaning tokens) onto the store
  ResultsList.push_back(atof(Results.c_str()));
  //Exactly the same operation with states, just using atoi to convert instead
  while(States .find(", ") != string::npos)  
  {  
    StatesList.push_back(atoi(States.substr(0, States .find(", ")).c_str()));  
    States = States.substr(States.find(", ") + 2);  
  }  
  StatesList.push_back(atoi(States.c_str()));
  return 0;
}