我正在编写一个关于字符串的c 程序。当我想大写字符串中的第一个单词和最后一个单词时,我遇到了麻烦。任何人都可以帮助我,拜托。非常感谢。这是我的代码:
#include <stdio.h>
void fun(int tc, char []);
int main() {
int tc;
char string[100];
printf("Enter tc: ");
scanf("%d", &tc);
fflush(stdin);
printf("Enter a string:\n");
gets(string);
printf("\nThe original string: \n%s", string);
fun(tc, string);
printf("\n\nThe string after processing: \n%s", string);
printf("\n\nOutput: \n%s", string);
return 0;
}
void fun(int tc ,char s[]) {
int c = 0;
int spaceCounter = 0; //First word not to be capitalized
while (s[c] != '\0')
{
if(tc == 1){
if ((spaceCounter == 0) && s[c] >= 'a' && s[c] <= 'z')
{
s[c] = s[c] - 32; // You can use toupper function for the same.
}
else if(s[c] == ' ')
{
spaceCounter++; //Reached the next word
}
c++;
}
}
}
最佳答案
假设您的字符串是s
。您可以从头开始大写,直到遇到空格,这意味着第一个单词结束。然后你可以找到字符串的结尾并开始向后处理,直到找到一个空格,这意味着最后一个单词结束。
void capitalize(char *s)
{
// capitalize first word
while (!isspace(*s))
{
*s = toupper(*s);
s++;
}
// reach end of s
while(*s++);
// capitalize last word
s--;
while (!isspace(*s))
{
*s = toupper(*s);
s--;
}
}
编辑:如果字符串至少有两个单词,则代码将起作用。在每个循环中添加对空终止符的检查以确保安全。
关于c - 如何在C程序中将字符串中的第一个单词和最后一个单词大写?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53032572/