Cody Rogers
Cody Rogers

Reputation: 85

lower case to Uppercase function - C

I've written this function to convert a lowercase str that is preset into it's uppercase variant. I've tried every different configuration I know that converts lower case to uppercase, however when I print it. It still ends up in lower case. So I am a tad Stuck.

char* stoupper(char str[]);

char str[100]= "uppercase";

printf("%s" , stoupper(str)); // Test to make sure it is working 

char* stoupper(char str[])
{ 
      int i = 0; 

      while(str[i] != '\0') 
      { 
                   if(str[i] >= 'A' && str[i] <= 'Z') 
                   str[i] = str[i] + ('A' - 'a'); 
                   i++; 
      }
      return str;
}  

/* I've tried various variations of this function this is just the one i had first */ 

Upvotes: 2

Views: 2862

Answers (4)

Namit Sinha
Namit Sinha

Reputation: 1445

your condition in if statement needs to be changed

if(str[i] >= 'A' && str[i] <= 'Z')

May I suggest another way to change Uppercase to lowercase and vice-versa

char* stoupper(char str[])
{ 
      for(int i=0;i<strlen(str);i++)
          if(!(str[i]>='A'&&str[i]<='Z')){
              str[i]=str[i]^' ';
          }

      return str;
} 

this method works because

[ASCII value of a lowercase character] XOR [ASCII value of ' '] =[ASCII value of that same character in UPPERCASE ]

Upvotes: 0

Digital Trauma
Digital Trauma

Reputation: 16016

I think your if condition should be:

if(str[i] >= 'a' && str[i] <= 'z') 

Upvotes: 1

75inchpianist
75inchpianist

Reputation: 4102

why are you reinventing the wheel? ctype.h is your friend

Use the toupper(int) method. Something like

char* stoupper(char str[]);

char str[100]= "uppercase";

printf("%s" , stoupper(str)); // Test to make sure it is working 

char* stoupper(char str[])
{ 
      int i = 0; 

      while(str[i]) 
      { 
          str[i]=toupper(str[i]);
          i++; 
      }
      return str;
}  

Upvotes: 2

Carl Norum
Carl Norum

Reputation: 225052

Your code only modifies already-uppercase letters, and turns them into who-knows-what (well, I'm sure you could figure out with an ASCII table). If you want to operate on lowercase letters, you need to change your if condition:

if (str[i] >= 'a' && str[i] <= 'z') 

Upvotes: 3

Related Questions