如何在字符串C程序中大写每个单词

时间:2018-10-18 11:59:45

标签: c string

我只是编写有关字符串的程序。我的问题是如何在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++;
    }
}

1 个答案:

答案 0 :(得分:0)

您需要使用空格计数器来跟踪单词。

如果空格计数器为奇数,则将字母大写,直到到达下一个单词。

示例:

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++;
  }
}