我在字符串中有空格分隔的整数,例如:
std::string s = "1 2 33 444 0 5";
Run Code Online (Sandbox Code Playgroud)
字符串格式良好:只有空格分隔的数字,没有任何字母、换行符等。
如何以STL方式计算上述字符串中的整数数量?我正在寻找将使用例如迭代器或<algorithm>.
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)
一个简单的方法是使用字符串流:
#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 值,例如,如果找到非数字字符(来自空格),它将停止计数。它也适用于多个空间。
此解决方案仅使用 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)
这是一个演示。
| 归档时间: |
|
| 查看次数: |
143 次 |
| 最近记录: |