C源代码,用于将字符串中的第一个字母从小写更改为大写

我有一个C源代码,但我有一个问题。 我想转换从小写到大写的字符串中的单词的第一个字母,但它将所有字母都更改为大写。 你能帮帮我解决这个问题吗?

#include  #include  #include  void main() { char sentence[100]; int count, ch, i; int str[32]; printf("Enter a sentence \n"); for (i = 0; (sentence[i] = getchar()) != '\n'; i++) { ; } sentence[i] = '\0'; /* shows the number of chars accepted in a sentence */ count = i; printf("The given sentence is : %s", sentence); printf("\n Case changed sentence is: "); for (i = 0; i < count; i++) { ch = islower(sentence[i])? toupper(sentence[i]) : tolower(sentence[i]); putchar(ch); } getch(); } 

例如

输入:欢迎来到谢里夫大学

期望的输出:欢迎来到谢里夫大学

实际产量:欢迎来到SHARIF大学

您必须检查当前字符是否为空格,然后仅在空格后使用字符上的toupper

 ch = ' '; for (i = 0; i < count; i++) { ch = isspace(ch) ? toupper(sentence[i]) : tolower(sentence[i]); putchar(ch); } 

请尝试以下代码。:)

 #include  #include  #define N 100 int main( void ) { char sentence[N]; char *p = sentence; printf( "Enter a sentence: " ); if ( !fgets( sentence, sizeof( sentence ), stdin ) ) sentence[0] = '\0'; printf( "\nThe given sentence is : %s", sentence ); do { while ( isblank( ( unsigned char )*p ) ) ++p; if ( islower( ( unsigned char )*p ) ) *p = toupper( *p ); while ( *p && !isblank( ( unsigned char )*p ) ) ++p; } while ( *p ); printf( "\nCase changed sentence is: %s", sentence ); return 0; } 

输出是

 The given sentence is : welcome to Sharif university Case changed sentence is: Welcome To Sharif University 

如果yor编译器不支持函数isblank那么您可以将其替换为isspace

似乎更正确的方法是仅使用isalpha因为在一般情况下,在空白之后可以存在例如数字或标点符号

 #include  #include  #define N 100 int main( void ) { char sentence[N]; char *p = sentence; printf( "Enter a sentence: " ); if ( !fgets( sentence, sizeof( sentence ), stdin ) ) sentence[0] = '\0'; printf( "\nThe given sentence is : %s", sentence ); do { while ( *p && !isalpha( ( unsigned char )*p ) ) ++p; if ( islower( ( unsigned char )*p ) ) *p = toupper( *p ); while ( isalpha( ( unsigned char )*p ) ) ++p; } while ( *p ); printf( "\nCase changed sentence is: %s", sentence ); return 0; } 

如果您不想更改原始字符串,则代码将如下所示

 #include  #include  #define N 100 int main( void ) { char sentence[N]; char *p = sentence; printf( "Enter a sentence: " ); if ( !fgets( sentence, sizeof( sentence ), stdin ) ) sentence[0] = '\0'; printf( "\nThe given sentence is : %s", sentence ); printf( "\nCase changed sentence is: " ); do { while ( *p && !isalpha( ( unsigned char )*p ) ) putchar( *p++ ); if ( islower( ( unsigned char )*p ) ) putchar( toupper( *p++ ) ); while ( isalpha( ( unsigned char )*p ) ) putchar( *p++ ); } while ( *p ); return 0; } 

您需要检查前面有空格的字符和大写字母。 您还需要检查第一个特殊情况,因为它前面没有空格。

 #include  #include  int main (void) { char str[] = "this is a test string"; int loop; for (loop=-1; loop<(int) strlen(str)-1; loop++) { // Possible upper case required? if (loop < 0 || str[loop]==' ') if (str[loop+1] >= 'a' && str[loop+1] <='z') str[loop+1] = (str[loop+1] - 'a') + 'A'; } printf ("string is : %s\n", str); return 0; } 

输出:

 string is : This Is A Test String