Converting strings that contain Uppercase letters to lower case letters

Go To StackoverFlow.com

-1

I need to be able to convert case in strings, so that "Hello" becomes "hello". Ultimately, I need to compare them.

How would I convert:

char *string = "HEllO";

to the string "hello"?

2012-04-04 23:42
by jenglee
What locale are you in - Edward Thomson 2012-04-04 23:45
What exactly do you wan to compare? Do you only need to know if the input string contains upper case letters - kay 2012-04-04 23:55
so do you eventually want to create a compareToIgnoreCase method? You can do that by converting the letters to lower case as you compare them and not saving the entire string - twain249 2012-04-04 23:55


3

First, your string is not declared properly, it should be:

char *string = "Hello";

Now, to convert to lowercase, try this:

char *lowercase(const char *str)
{
    int length = strlen(str);
    char *dup = malloc(length + 1);
    strcpy(dup, str);

    for (int i = 0; i < length; i++)
    {
         dup[i] = tolower(dup[i]);
    }

    return dup; // remember to free when done!
}
2012-04-04 23:44
by Richard J. Ross III
what's wrong with his definition of the string? "HEllO" is a valid string - twain249 2012-04-04 23:54
I guess Richard meant revision 3 of your question - kay 2012-04-05 00:03


2

Simply perform this inline.

   char string[] = "Hello";
   char * ptr;

   for (ptr = string; *ptr != '\0'; ++ptr)
   {
       *ptr = tolower(*ptr);
   }
2012-04-04 23:49
by junglecat
String literals are const. You will have a seg fault at runtime with your code. char string[] = ... would work - kay 2012-04-04 23:50
(edit: kay got there before me) At least explain to him why this won't wor - James 2012-04-04 23:52
Corrected, yes the behavior would be "undefined" - junglecat 2012-04-04 23:58
Ads