对于输入的每个字符串,查找其中的最大字母,在该字母后面插入字符串“(max)”。
Input
输入数据包括多个测试实例,每个实例由一行长度不超过100的字符串组成,字符串仅由大小写字母构成。
Output
对于每个测试实例输出一行字符串,输出的结果是插入字符串“(max)”后的结果,如果存在多个最大的字母,就在每一个最大字母后面都插入"(max)"。
Sample Input
abcdefgfedcba
xxxxx
Sample Output
abcdefg(max)fedcba
x(max)x(max)x(max)x(max)x(max)
这是更为简单的AC代码:根据这个字符串只要输出一个结果就行了。
# include<stdio.h>
#include<string.h>
int main()
{
int n, i, j, catcount, subscript, temp;
char a[300], b[1000], c[10] = {"(max)"}, maxchar;
while(gets(a))
{
maxchar = a[0];
for(i = 0; a[i] != '\0'; i++)
if(a[i] >= maxchar)
maxchar = a[i];
for(i = 0; i < strlen(a); i++)
{
printf("%c", a[i]);
if(a[i] == maxchar)
printf("(max)");
}
printf("\n");
}
return 0;
}
末尾并不需要对a数组清零,清成全'\0'。
这是我自己写的:学长说,这个代码他看了很难受。看了我自己的代码,我也很难受。
# include<stdio.h>
#include<string.h>
int main()
{
int n, i, j, catcount, subscript, temp;
char a[300], b[1000], c[10] = {"(max)"}, maxchar;
while(gets(a))
{
maxchar = a[0];
for(i = 0; a[i] != '\0'; i++)
if(a[i] >= maxchar)
maxchar = a[i];
catcount = 0;
for(i = 0; a[i] != '\0'; i++)
{
if(a[i] == maxchar)
{
temp = i;
strncat(b, a + strlen(b) - 5*catcount, i - (strlen(b) - 5*catcount) + 1);///说明b是空的使用strncat不受影响,当b是空的时相当于strnccpy。
catcount++;
strcat(b, c);
//strcat(b, a + i + 1);这句不能放这里,否则对于一组全相同字母测试例子第一次插入(max)后会把后面的相同字母全拼到b里去。
}
}
strcat(b, a + temp + 1);///使用temp可以把最后一个最大字母的下标记下来。在把最后一个最大字母后面插入(max)之后,就可以用这句把最后一个最大字母后面的字符全拼到b里去了。
puts(b);
memset(a, '\0', sizeof(a));
memset(b, '\0', sizeof(b));
}
return 0;
}