Search code examples
carrayspointerstoupper

Can't convert lowercase to uppercase with pointer


So I want to make lowercase letters to uppercase with one condition, before the lowercase letter there must be space, but the problem is I can't check if the next char in the array(using +1) is a space or not.

#include <stdio.h>
#include <ctype.h>

void convertToUpper( char *array );

int main()
{   
   char x[] = "i believe i can do it";
   convertToUpper(x);
   printf("%s",x);

   return 0;
}

void convertToUpper( char *array )
{
   while( *array != '\0' )
   {        
       if( *( array + 1 ) != ' ' && *array == ' ' )
       {
           *( ++array) = toupper( *(array) );   
       }
      ++array;
   }
}

Solution

  • You are simply convert the wrong character, because in your condition, *array is space, you should convert the letter after it:

    while(*array != '\0')
    {        
        if( *(array + 1) != ' ' && *array == ' ')
            *(array + 1) = toupper(*(array + 1));
        ++array;
    }
    

    This simple check won't work for the 1st char, if it should be upper case too, add following before the loop:

    if (*array != ' ')
        *array = toupper(*array)