c++ 怎样提取一个字符串中的连续数字并放到另一个数组中保存? 急!

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c++ 怎样提取一个字符串中的连续数字并放到另一个数组中保存? 急!相关的知识,希望对你有一定的参考价值。

1、 从键盘输入字符串,内有数字和非数字字符(以空字符串作为输入结束标志),如:A32b2K456 178? Fgfre54f,将其中的连续数字作为一个整数,依次存入数组a中,例如a[0]中存32、a[1]中存2、a[2]中存456、……
不考虑0开头情况。
请不要引用系统的那些高级函数,就用基本方法做。 我才学c一学期呢 。 谢谢 可以追加。

参考技术A char str_example[] = "a123x456__17960?302ab5876";
char* p_str = str_example;
int n = strlen(str_example);
int a[100] = 0 ;
int cout1 = 0;
int j = 0;

for (int i = 0; i < n;)

int sum = 0;
while(isdigit(*p_str))

sum = sum*10+(*p_str++-'0');
i++;

a[i] = sum;
i++;
p_str += 1;

for (int i = 0; i < 100; i++)

if (a[i] != 0)

a[j++] = a[i];
cout1 += 1;


cout << "这个字符串中有以下整数:" << endl;
for (int i = 0; i < j; i++)

cout << a[i]<<endl;

cout <<"整数的个数为:"<<cout1 << endl;
cout << atoi(str_example) << endl;
return 0;
参考技术B 额。我感觉好像没有那么复杂吧?你觉得这样行不?
#includecctype
#includecstring
#includeiostream
using namespace std ;
#define Len 20
int main()

int j = 0 ;
char str[Len] ;
char sub[Len] ;
char* p ;
gets(str) ;
for( p = str ; *p ; p ++ )
if(isdigit(*p))
*(sub + j++ ) = *p ;
sub[j] = '\0' ;
puts(sub) ;
return 0 ;
本回答被提问者和网友采纳
参考技术C #include <stdio.h>
#include <string.h>

void get_values_from_string(const char *str, int *rst_arr, size_t len)

const char *num_start = NULL, *num_end = NULL;
const char *numbers = "123456789"; // char sequence denote the first digit of value
int count = 0;

num_start = strpbrk(str, numbers); // find the num_start of value
while(num_start)
num_end = num_start;
while(*num_end>='0'&&*num_end<='9'&&*num_end!='\0')
++num_end; // move num_end to the end position of value, [num_start, num_end) denotes the range of value

if(count < len) // make sure rst_arr has enough space
rst_arr[count++] = atoi(num_start);

num_start = strpbrk(num_end,numbers); // do the next find

参考技术D #include <stdio.h>
#define N 10000
void main()

char str[N];
int a[N],i=0,j=0,k=0;
do

scanf("%c",&str[i]);
i++;
while (str[i-1]!=' ');
for (i=0;str[i]!=' ';)

a[k]=0;
for (j=i;str[j]>='0' && str[j]<='9';j++)
a[k]=a[k]*10+str[j]-'0';
if(j>i) k++; i=j;
if(j==i) i++;

for (i=0;i<k;i++)
printf("a[%d]=%d ",i,a[i]);

第5个回答  2010-09-07 #include <stdio.h>
#include <stdlib.h>
#include <string.h>

void main(void)

char szStr[1024];
int i = 0;
int iArr[1024];
char tmpNum[1024];

printf("输入一个字符串,包括字母和数字 : ");
scanf("%s",szStr);

int j = 0;
int k = 0;
tmpNum[0] = '\0';
for ( i = 0 ; i < 1024 ; i++ )

if ( szStr[i] >= '0' && szStr[i] <= '9' )

tmpNum[j] = szStr[i];
j++;
tmpNum[j] = '\0';

else

if ( strlen(tmpNum) > 0 )

//获取数值
iArr[k] = atoi(tmpNum);
k++;
j = 0;
tmpNum[0] = '\0';



if ( szStr[i] == '\0' )

//字符串已处理完,退出
break;



printf("里面包含数字:\n");
for ( i = 0 ; i < k ; i++ )

printf("%d ",iArr[i]);

以上是关于c++ 怎样提取一个字符串中的连续数字并放到另一个数组中保存? 急!的主要内容,如果未能解决你的问题,请参考以下文章

如何用c/c++把一个字符串把里边的数字提取出来

c++提取2维数组

excel表格怎样提取另一个表格中的对应数据?

遍历一串字符并提取数字?

sql 提取第一个字符

在C++中,如何只保留字符串中的数字而去除字母和符号,请给出示例语句,谢谢