試試下面的代碼:)
#include <stdio.h>
#include <ctype.h>
#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
如果侑編譯器不支持功能isblank
那麼你。可以代替itute它isspace
似乎更正確的方法將只有isalpha
使用,因爲在一般情況下,後一個空白可以有例如一個數字或標點符號
#include <stdio.h>
#include <ctype.h>
#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 <stdio.h>
#include <ctype.h>
#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;
}
這是因爲你正在改變所有字符爲大寫:'for(i = 0;我
m0skit0
2014-12-03 16:50:27
[C中每個單詞的第一個字母的簡單大寫]的可能重複(http://stackoverflow.com/questions/20038297/simple-capitalization-of-first-letter-of-each-word-in-c) – b4hand 2014-12-03 17:54:27