How to use tolower() with char*?

12.2k views Asked by At

I have a .txt file with some words and I need them to be lowercase. How to make each word lowercase? Just adding tolower() to strtok() doesn't work. What should I add? Or maybe it would be easier to use tolower() on whole file firstly? But how? Please help!

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//#include <ctype.h>

int main(void)
{
    char str[5000];
    char *ptr;
    char *words[5000];
    FILE * fp = fopen("hi.txt", "r");
    fgets(str, 49, fp);             
    ptr = strtok(str, ",.; ");         
    int i = 0;
    while(ptr != NULL)  
    {
        words[i]= ptr;
        i++;
        ptr = strtok(NULL, ",.; "); 
    }
    fclose(fp);

    for(int j=0;j<i;j++) {
        printf("%s\n", words[j]);
        //printf("%s\n", tolower(words[j])); // Doesn't work!
    }
    return 0;
}

Example:

hi.txt

Foo;
Bar.
Baz.

Expected output

foo
bar
baz
3

There are 3 answers

2
chad On BEST ANSWER

The tolower function takes a single character and makes it lower case, so calling it on a char* doesn't really make sense. If you know that only the first character of each substring returned by strtok is upper case, you need to call tolower on that character specifically within your loop. In other words, something like this:

while(ptr != NULL)  
{
    ptr[0] = tolower((unsigned char) ptr[0]);
    /* 
    Or equivalently ...
    *ptr = tolower((unsigned char) *ptr)
    */
    words[i]= ptr;
    i++;
    ptr = strtok(NULL, ",.; "); 
}

If there are more characters in the string that could be upper case and you want to make sure that they become lower case, you need to iterate through the substring and call tolower on every character:

while(ptr != NULL)  
{
    for (char *ch = ptr; *ch; ch++)
    {
        *ch = tolower((unsigned char) *ch);
    }
    words[i]= ptr;
    i++;
    ptr = strtok(NULL, ",.; "); 
}
2
MD XF On

Since you asked about tolower, you could try looping through a string character by character:

int i, s = strlen(upperString);
for (i = 0; i < s; i++)
    lowerString[i] = tolower(upperString[i]);

If you don't need to use tolower, you can use strlwr to convert an entire string to lowercase (if it's implemented on your system - strlwr isn't standard C).

7
sameera sy On

tolower() works only for single characters. You can make use of the below function to convert strings to lower case:

printf("%s\n", cnvtolwr(mystring));

The implementation of the function is as below.

char *cnvtolwr(char *str)
{
    unsigned char *mystr = (unsigned char *)str;

    while (*mystr) {
        *mystr = tolower(*mystr);
        mystr++;
    }
    return str;
}