C语言:下面要求的C程序怎么编?

编写程序将一个小写英文字符串重新排列,按字符出现的顺序将所有相同字符存放在一起。如:acbabca排列后为:aaaccbb。
要求:输入出错时要求提示重新输入该字符。

先定义一个字符型数组,把这一串字符串都进去,以后撤出他的串长,然后对这个字符串以字符为单位进行一次冒泡排序就可以了。具体的程序代码和运行情况见图片。

程序代码文本:

#include<stdio.h>

int main()

{ int i,j,n;

  char s[100],t;

  scanf("%s",s);

  for(n=0; s[n]; n++);

  for(i=0; i<n-1; i++)

    for(j=0; j<n-1-i; j++)

      if(s[j]>s[j+1])

      { t=s[j];

        s[j]=s[j+1];

        s[j+1]=t;

      }

  puts(s);

  return 0;

}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2021-11-19

哈哈,刚才回答了同样的问题,你没有看见,因为被“违规”了。

代码文本:

#include "stdio.h"

#define N 81

int main(int argc,char *argv[]){

char s[N],i,j,k,t;

puts("Please enter a string composed of lowercase letters...");

for(i=0;i<N;i++){

if((t=getchar())!=EOF && t>='a' && t<='z')

s[i]=t;

else if(t=='\n')

break;

else{

printf("Error, enter again this character: ");

i--;

}

}

s[i]='\0';

printf("The string you input is '%s'\nAfter rearrangement is '",s);

for(i=0;s[i];i++){

for(j=i+1;s[j];j++)

if(s[i]==s[j]){

for(k=s[j];j>i;s[j--]=s[j-1]);

s[j+1]=k;

break;

}

putchar(s[i]);

}

printf("'\n");

return 0; 

}

本回答被提问者采纳
第2个回答  2021-11-19
#include <stdio.h>
#include <conio.h>
int main()
{
int ord[26],cnt[26];
for (int i=0;i<26;i++) ord[i]=cnt[i]=0;
while(1)
{
int ch=getch();
if (ch=='\n' || ch=='\r') break;
else if (ch<'a' || ch>'z') {
printf("%c 输入错误,重新来过!\n",ch);
continue;
}
else {
int id=-1;
for (int i=0;i<26;i++) {
if (ord[i]==0 && id<0)
{
id=i;
break;
}
if (ord[i]==ch)
{
cnt[i]++;
break;
}
}
if (id>=0) {
ord[id]=ch;
cnt[id]=1;
}
}
}
for (int i=0;ord[i];i++)
for (int j=0;j<cnt[i];j++) printf("%c",ord[i]);
}
输入不带回显的版本