使用标准库计算字符串中的十进制数

wen*_*eno 3 c++

我在字符串中有空格分隔的整数,例如:

std::string s = "1 2 33 444 0 5";
Run Code Online (Sandbox Code Playgroud)

字符串格式良好:只有空格分隔的数字,没有任何字母、换行符等。


如何以STL方式计算上述字符串中的整数数量?我正在寻找将使用例如迭代器或<algorithm>.

Man*_*oor 7

std::count_if(s.begin(),s.end(), [](unsigned char c){ return std::isspace(c);}) + 1


编辑:

如果字符之间有多个/不同的空格,则可以将 lambda 更改为:

    [](unsigned int c)
    { 
        static bool prev = false;
        bool current = isspace(c);
        bool new_space = !prev && current;
        prev = current;
        
        return new_space;
    }
Run Code Online (Sandbox Code Playgroud)


ana*_*ciu 5

一个简单的方法是使用字符串流:

#include <iostream>
#include <sstream>

int main()
{
    int temp;
    int count = 0;
    std::string s = "1 2 33 444 0 5";

    std::stringstream ss(s);
    while(ss >> temp){
        count++;
    }
    std::cout << count; //test print
    return EXIT_SUCCESS;
}
Run Code Online (Sandbox Code Playgroud)

请注意,这只会计算 parseabe 值,例如,如果找到非数字字符(来自空格),它将停止计数。它也适用于多个空间。

  • +1 到目前为止,这是唯一不假设字符由一定数量的空格字符分隔的答案,只是假设数字由空格分隔。 (3认同)
  • @PaulMcKenzie,我很欣赏明确的赞扬,谢谢。 (3认同)

cig*_*ien 5

此解决方案仅使用 STL,没有循环,并且将处理任意数量的前导、尾随和额外空格:

std::string s = "1 2 33 444 0 5";
std::stringstream ss(s);

int const count = std::distance(std::istream_iterator<int>{ss},
                                std::istream_iterator<int>{}); 
Run Code Online (Sandbox Code Playgroud)

这是一个演示