字符串中的数字
-
总时间限制:
- 1000ms 内存限制:
- 65536kB
-
描述
- 输入一个字符串,长度不超过20,字符串中包含数字和非数字字符,将其中是数字的字符提取出来,对它们进行从小到大排序,非数字字符则忽略不计。 输入
- 若干行字符串 输出
-
每一个字符串中所有数字的升序排序。每个数字占四个字符位置。使用cout<< setw(4)<< num;
处理完一行字符串换行一次。使用cout<< endl;
样例输入
-
31W 7Q9 2D2 4d t51 X9P
样例输出
-
1 2 2 3 7 9 1 4 5 9
提示
-
1.由于有多组测试数据,要求使用while循环读取输入。如下:
while(cin.getline(str,21))
{
//你的代码
}
2.setw(4)函数需要#include < iomanip >
问题链接:Bailian2888 字符串中的数字
问题分析:一是要求把数字找出来,及(0 到 9)较为简单,然后将这些数字排序输出,因为题中已要求宽度为四输出,所以就剩怎么实现了,我想的是借用数组,首先先循环读入,便输入边处理,将数字挑出来放到数组中去,然后在进行排序,冒泡,快速等,(冒泡记住是从小到大排序)程序说明:排序和输出格式宽度为4是关键。
题记:按照提示来
AC
的程序
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 20
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
char s[N + 1], t[N+1];
int main()
{
int i , n;
i = 0;
n = 0;
while(gets(t))
{
n = 0;
for(i = 0;i<strlen(t);i++)
{
if(t[i]>= '0'&& t[i] <= '9')
s[n++] = t[i];
}
char t;
int a,j;
a = 0;
j = 0;
for(a = 0;a < n;a++)
for(j = 0;j <= a;j++)
{
if(s[a] < s[j])
{
t = s[a];
s[a] = s[j];
s[j] = t;
}
}
for(j = 0; j < n; ++j)
printf("%4c", s[j]);
printf("\n");
}
return 0;
}
/*while循环用gets()可以实现行处理,知道遇到终止符,排序算法自己在搞一搞*/