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

C++ 使用标准库计算字符串中的十进制数,c++,C++,我在字符串中有空格分隔整数,例如: std::string s = "1 2 33 444 0 5"; 字符串格式良好:只有空格分隔的数字,没有任何字母、新行等 如何以STL方式计算上述字符串中的整数数?我正在寻找一些“简短”的东西,例如迭代器或std::count_如果(s.begin(),s.end(),[](unsigned char c){return std::isspace(c);})+1 编辑: 如果字符之间有多个/不同的空格,则可以将lambda更改为: [](un

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

std::string s = "1 2 33 444 0 5";
字符串格式良好:只有空格分隔的数字,没有任何字母、新行等


如何以STL方式计算上述字符串中的整数数?我正在寻找一些“简短”的东西,例如迭代器或
std::count_如果(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;
    }

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

#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;
}
#包括
#包括
int main()
{
内部温度;
整数计数=0;
std::string s=“1 2 33 444 0 5”;
标准::stringstream ss(s);
而(ss>>温度){
计数++;
}

std::cout是否保证每个整数由单个空格字符分隔(没有前导或尾随空格)

如果是这样,那么您只需要在字符串本身的空白字符数上加1,因为空字符串是一个特例

#include <algorithm>

size_t intCount(const std::string& s) {
  if (s.size() == 0) {
    return 0;
  }

  return std::count(s.begin(), s.end(), ‘ ‘) + 1;
}
#包括
大小\u t整数(常量标准::字符串和字符串){
如果(s.size()==0){
返回0;
}
返回std::count(s.begin()、s.end()、“”)+1;
}

您可以使用正则表达式:

#include <iterator>
#include <regex>
#include <string>

std::string s = "1 2 33 444 0 5";

const std::regex regex("\\d+");
const auto n = std::distance(
    std::sregex_iterator(s.begin(), s.end(), regex),
    std::sregex_iterator());
#包括
#包括
#包括
std::string s=“1 2 33 444 0 5”;
常量std::regex regex(\\d+);
常数自动n=标准::距离(
std::sregex_迭代器(s.begin()、s.end()、regex),
std::sregex_迭代器();

这将自动处理多个前导和尾随空格。此方法不会对每个整数的长度施加任何限制。

此解决方案仅使用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>{}); 
std::string s=“1 2 33 444 0 5”;
标准::stringstream ss(s);
int const count=std::distance(std::istream_迭代器{ss},
std::istream_迭代器{});

这是一个./p> <代码>返回SUpType(0):……;/>代码>也可以考虑<代码> STD::StrigyVIEW 按值。+ 1。这是唯一的答案,它不假设字符被一组空白字符分隔开来,只是数字被空白分隔开来。@ PulcMcKunZi,谢谢您的明确表扬,谢谢。