我和我的朋友通过从互联网上捕捉算法为C编写了代码。我们的程序运行良好,但在某些情况下,我们的长代码有运行时错误。你能帮我把这段代码缩短吗? 此代码使用大写和小写字母捕获名称,并将单词的首字母转换为大写,其他字母转换为小写。首先,我们应该给出我们想要的名字数量。
#include <stdio.h>
#include <ctype.h>
int ch, i,n,tool[100];
int main()
{
int k, j , i;
char sentence[100][100];
scanf("%d",&n);
for(k=0;k<n+1;k++) {
for (i = 0; (sentence[k][i] = getchar()) != '\n'; i++) {
;
}
sentence[k][i] = '\0';
tool[k]=i;
ch=toupper(sentence[k][0]);
sentence[k][0]=ch;
for (j = 1; j < i; j++) {
if(sentence[k][j-1]==' ')
ch=toupper(sentence[k][j]);
else
ch=tolower(sentence[k][j]);
sentence[k][j]=ch;
}
}
for(i=0;i<n+1;i++) {
for(j=0;j<tool[i];j++) {
ch=sentence[i][j];
putchar(ch);
}
printf("\n");
}
return 0;
}
答案 0 :(得分:2)
试试这个..
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
char *name,*backup_addr, **name_array;
int i,n,j;
main()
{
char c;
scanf("%d",&n);
name_array=malloc(sizeof(char)*1000);
for(i=0;i<n;i++)
{
name_array[i]=malloc(sizeof(char));
backup_addr=name=malloc(sizeof(char*));
while(isspace(c=getchar()));
if(isalpha(c))
{
*name++=toupper(c);
for(j=0;(isalpha(c=getchar()))!='\n'&&c!='\n';j++,name++)
*name=tolower(c);
}
*name='\0';
name=backup_addr;
name_array[i]=name;
}
for(i=0;i<n;i++)
printf("%s\n",name_array[i]);
}
答案 1 :(得分:1)
这是一个明显更短的。并且在方便的功能形式中:
#include <stdio.h>
/** convert string to sentence case.
* returns string with initial cap and single i converted to uppercase.
*/
char *str2sentence (char *str)
{
if (!str) return NULL;
char *p = str;
if ('a' <= *p && *p <= 'z') /* convert first to upper */
*p -= 32;
p++;
for ( ; *p; p++) /* convert remaining to lower, except a single 'i' to upper 'I' */
{
if (*(p - 1) == 0x20 && *(p + 1) == 0x20)
{
if (*p == 'i')
*p -= 32;
else
if ('A' <= *p && *p <= 'Z' && *p != 'I')
*p += 32;
}
else
if ('A' <= *p && *p <= 'Z')
*p += 32;
}
return str;
}
int main (void) {
char *str = NULL;
printf ("\n Enter a string to convert to sentence case ([enter] to quit)\n");
while (printf ("\n input : ") && scanf ("%m[^\n]%*c", &str) == 1)
printf (" result: %s\n", str2sentence (str));
return 0;
}
<强>输出:强>
./bin/str2sentence
Enter a string to convert to sentence case ([enter] to quit)
input : this IS A StrinG tO ConvERt.
result: This is a string to convert.
input : oR maYBe aNOTher OnE.
result: Or maybe another one.
input :
答案 2 :(得分:1)
你可以试试这个。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
main()
{
char *array[100],*p;
int i=0,j,n,k;
scanf("%d",&n);
for (n=n+1 ; n > 0 ; n--) { p=(char *)malloc(100);
array[i++]=p;
for (k=0; (*p=getchar()) != '\n' && *p !=EOF ;p++, k++); *p='\0';
for ( p=p-k; *p !='\0'; p++) {
if (isspace(*p) )
continue;
*p=toupper(*p); p++;
for( ; *p!=' ' && *p!='\0' ;p++ )
*p=tolower(*p);
if ( *p=='\0' ) p--;
}
}
for (j=0; j<i ; j++)
printf("%s\n",array[j]);
}
输入就像你的程序一样。