输入一个字符串,长度不超过20,字符串中包含数字和非数字字符,将其中是数字的字符提取出来,对它们进行从小到大排序,非数字字符则忽略不计。
Input
若干行字符串
Output
每一个字符串中所有数字的升序排序。每个数字占四个字符位置。使用cout<< setw(4)<< num;
处理完一行字符串换行一次。使用cout<< endl;
Sample Input
31W 7Q9 2D2
4d t51 X9P
Sample Output
1 2 2 3 7 9
1 4 5 9
Hint
1.由于有多组测试数据,要求使用while循环读取输入。如下:
while(cin.getline(str,21))
{
//你的代码
}
2.setw(4)函数需要#include < iomanip >
#include<stdio.h>
#include<string.h>
int main() {
int i, j, len, t, s;
char a[21], b[21], temp;
while (gets(a) != NULL) //用fgets会出现presentation error
{
len = strlen(a);
j = 0;
for (i = 0; i < len; i++) //for (i = 0; a[i]; i++)
{
if (a[i] >= '0'&&a[i] <= '9')
{
b[j] = a[i];
t = j;
j++;
}
s = j-1; // 也可不用变量t,直接用j,后面的冒泡用另一变量;若用,必须增加变量s
}
//冒泡排序
for (i = 0; i < t; i++)
for (j = 0; j < t - i; j++)
if (b[j] > b[j + 1])
{
temp = b[j];
b[j] = b[j + 1];
b[j + 1] = temp;
}
t = s;// 增加的s就是为这准备的,否则WA,坑
for (i = 0; i < t; i++)
printf("%4c", b[i]);
if (i == t)
printf("%4c\n", b[i]);
else printf("\n");
}
return 0;
}
j++是先取j的值,后使j的值加1;
++j是先将j的值加1,后取用j的值
%c是只输出字符本身。
%4c输出占4位,要输出的字符在最右侧,前面有三个空格。