我想计算字符串/c++中的数字

I would like to count the numbers in a string /c++

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

我试过计算字符串中的数字,但它不起作用,我认为这在逻辑上是好的。我是一个编程初学者。我知道它适用于一位数,但这是故意的。

#include <iostream>
#include <string.h>
#include <vector>
using namespace std;
int main() 
{
    int numbs [10] = {0,1,2,3,4,5,6,7,8,9};
    string str1;
    cin >> str1;
    vector <unsigned int> positions;
    for (int a = 0 ;a <=10;a++) 
    {
        int f = numbs[a];
        string b = to_string(f);      
        unsigned pos = str1.find(b,0);
        while(pos !=string::npos)
        {
            positions.push_back(pos);
            pos = str1.find(b,pos+1);
            break;
        }
    }
    cout << "The count of numbers:" << positions.size() <<endl;
    return 0;
 }

如果只需要计算字符串中的数字,那么使用std::vector是没有意义的。不用向量也可以数。例如

#include <iostream>
#include <string>
int main() 
{
    std::string s( "A12B345C789" );
    size_t count = 0;
    for ( std::string::size_type pos = 0;
          ( pos = s.find_first_of( "0123456789", pos ) ) != std::string::npos;
          ++pos )
    {
        ++count;
    }     
    std::cout << "The count of numbers: " << count << std::endl;
    return 0;
}

输出为

The count of numbers: 8

也可以使用标头<algorithm>

中定义的标准算法std::count_if例如

#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>
int main() 
{
    std::string s( "A12B345C789" );
    size_t count = std::count_if( s.begin(), s.end(), 
                                  []( char c ) { return std::isdigit( c ); } );
    std::cout << "The count of numbers: " << count << std::endl;
    return 0;
}

输出为

The count of numbers: 8

如果你需要计算数字而不是字符串中的数字,那么你应该使用标准的C函数strtol或c++函数std::stoi

使用子字符串以分隔符(通常为空格)提取字符串的每个部分。然后将每个子字符串转换为数字。限定和转换的可能是字符串中的数字。

您可能还对c++函数"isdigit"感兴趣:

  • http://www.cplusplus.com/reference/locale/isdigit/
例如:

include <iostream>
#include <string.h>
#include <vector>
#include <locale>    // std::locale, std::isdigit
using namespace std;
int main() 
{
  // Initialze array with count for each digit, 0 .. 9
  int counts[10] = {0, 0, 0, 0, 0, 0, 0,0, 0, 0 };
  int total = 0;
  // Read input string
  string str;
  cin >> str;
  // Parse each character in the string.  
  std::locale loc;
  for (int i=0; i < str.length(); i++) {
        if isdigit (str[i], loc) {
          int idx = (int)str[i];
          counts[idx]++
          total++;
  }
  // Print results
  cout << "The #/digits found in << str << " is:" << total << endl;   
  // If you wanted, you could also print the total for each digit ...
  return 0;
}