我刚刚编写了一个关于字符串的程序。我的问题是如何在 c 中字符串的偶数位置处大写单词。我的逻辑是一个词甚至可以整除2等于0。任何人都可以帮助我,非常感谢。这是我的代码:
#include <stdio.h>
void upper_string(char []);
int main()
{
char string[100];
printf("Enter a string to convert it into upper case\n");
gets(string);
upper_string(string);
printf("The string in upper case: %s\n", string);
return 0;
}
void upper_string(char s[]) {
int c = 0;
while (s[c] != '\0') {
if (s[c] >= 'a' && s[c] <= 'z')
{
s[c] = s[c] - 32;
}
c++;
}
}
最佳答案
您需要使用空格计数器来跟踪单词。
如果空格计数器为奇数,则将字母大写,直到到达下一个单词。
示例:
void upper_string(char s[]) {
int c = 0;
int spaceCounter = 0; //First word not to be capitalized
while (s[c] != '\0')
{
if ((spaceCounter %2 == 1) && 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++;
}
}
关于c - 如何将字符串c程序中的每个单词大写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52873497/