判断字符串中有多少个整数
输入一个字符串,内有数字和非数字字符,判断字符串中有多少个整数,连续的数字算一个整数
#include<iostream>
#include<string>
#include<iomanip>
using namespace std;
//该函数将字符串中的连续数字存入整型数组a中,并返回a中整数的个数
int findInteger(char* p, int* a)
{
int j, n = 0, i, k;
char temp[100];//存放连续的数字,以便转换成整数
for (i = 0;p[i] != '\0';i++) // '0'表示字符串结束符
{
j = 0;
while (p[i] >= '0' && p[i] <= '9')//比较ASCII码,判断第i个字符是否是数字
{
temp[j] = p[i];//是的话,存入temp数组
j++;
i++;
}
if (j != 0)//如果存在连续的数字
{
*a = atoi(temp);//atoi函数的功能是将字符串转换成正整数
a++;
n++;
for (k = 0;k < j;k++)//将数组temp清零,以便存放下一个数字
temp[k] = 0;
i--;
}
}
return n;
}
int main()
{
int i, m, a[100];
char line[100];
cout << "请输入一个字符串:" << endl;
cin >> line;
m = findInteger(line, a);
cout << "字符串中共有:" << m << "个整数" << endl;
for (i = 0;i < m;i++)
{
cout << a[i] << endl;
}
cout << endl;
system("pause");
return 0;
}
转载自:黑凤梨の博客