如何在字符串中查找值并将其转换为整数?

时间:2014-08-10 00:29:40

标签: c++ string int

我的字符串是#34;我有5支铅笔,汤姆有3支铅笔"。 如何在字符串中找到值然后将它们转换为整数?

2 个答案:

答案 0 :(得分:1)

你需要std :: string和regex(std :: regex现在不起作用,所以使用boost)来分隔数字。您的典型算法是:

  1. 创建boost :: regex以分隔数字。
  2. 使用boost :: regex_search获取您的号码。
  3. 使用std :: stoi将字符串转换为整数。
  4. 示例代码为:

    #include <iostream>
    #include <string>
    #include <boost/regex.hpp>
    
    int main ()
    {
      std::string s ("I have 5 pencils and Tom have 3 pencils");
      boost::smatch m;
      boost::regex e("[0-9]+");
    
      std::cout << "Target sequence: " << s << std::endl;
      std::cout << "Regular expression: /[0..9]+/" << std::endl;
      std::cout << "The following matches and submatches were found:" << std::endl;
    
      while (boost::regex_search (s, m, e))
      {
        for (auto x : m)
          std::cout << std::stoi(x) << " ";
    
        std::cout << std::endl;
        s = m.suffix().str();
      }
    
       return 0;
    }
    

    构建它的简单Makefile:

    CC=g++
    FLAGS=-std=c++11
    LIBS=-lboost_regex
    
    test: test.cpp
            $(CC) $(FLAGS) $(LIBS) test.cpp -o test
    

    您应该安装boost或使用您选择的正则表达式库。

答案 1 :(得分:0)

您可以尝试进行标记化。

创建令牌和Token_stream类。

class Token
{
public:
    /* Implementation of the class */

private:
    char token_type;    // (e.g. store a letter such as 'a' for alphabetic
                        // characters and a number such as '8' for numbers)

    char letter;    // store which letter or ...
    int number;     // ... which number
}

class Token_stream
{
public:
    /* Implementation */

private:
    vector<Token> tokens;
}

将字符串中包含的每个字符存储在一个不同的Token中,然后将Tokens存储到Token_stream中。然后检查Token_stream中的每个令牌,以确定它的类型是数字还是字母字符。如果它是一个数字,而不是将它的值存储在一个int的向量中,否则检查流中的下一个Token。

OR

使用range-for循环,检查存储在字符串中的每个字符,如果是数字,则将其存储在int中。

string s;
getline(cin, s);

vector<int> numbers;

for (char c : s)
{
    if (48 <= c && c <= 57)    // ASCII values for characters of numbers 48 == '0',
    {                          // 49 == '1', ..., 57 == '9'
        cin.putback(c);    // put c back into the standard input, so that you can 
                           // read it again as an int

        int n;
        cin >> n;

        numbers.push_back(n);
    }
}