PoorProgrammer
PoorProgrammer

Reputation: 111

How to use tolower() with char*?

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

Upvotes: 3

Views: 13012

Answers (3)

chad
chad

Reputation: 395

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, ",.; "); 
}

Upvotes: 5

MD XF
MD XF

Reputation: 8129

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).

Upvotes: 0

sameera sy
sameera sy

Reputation: 1718

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;
}

Upvotes: 4

Related Questions