0

I just code a program about string. My problem is how can I capitalize word at even number position of a string in c. My logic is a word at even can divide 2 equal 0. anyone can help me please, thank so much. here is my code:

#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++;
    }
}
Mika Fischer
  • 4,058
  • 1
  • 26
  • 28
An Mạnh
  • 31
  • 6
  • Don't use `gets` use `fgets` instead. `My logic is a word at even can divide 2 equal 0` no you should use `%` (modulus) operator. – kiran Biradar Oct 18 '18 at 12:03
  • 1
    Are you saying you need to capitalize every 2nd word? You will obviously need to look for spaces then, in order to separate words, or [use `strtok`](https://stackoverflow.com/q/3889992/69809). – vgru Oct 18 '18 at 12:04
  • even number position word in a string, such as hello world how are you today, so the world will be capitalized: world, are, today – An Mạnh Oct 18 '18 at 12:09
  • 1
    You seem to be assuming that input will be ASCII. That's not universal in C - you'd be safer using `toupper()` (in ``) for the conversion. And you'd no longer need to write your own buggy `isalpha()`. – Toby Speight Oct 18 '18 at 14:24
  • Oh, and **never** use `gets()` - it's fundamentally unsafe. Only accept input using functions that won't overrun the bounds. – Toby Speight Oct 18 '18 at 14:25

1 Answers1

0

You need to use space counter to keep track of the words.

if space counter is odd then capitalize the letters until you reach the next word.

Example:

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++;
  }
}
kiran Biradar
  • 12,700
  • 3
  • 19
  • 44