Home > Net >  upper case to lowercase
upper case to lowercase

Time:08-25

I just started learning programming, and I started with C, and I am just goofing around and trying to make a function that changes a letters in a string from uppercase to all lowercase, and then return it in an array of lowercase letters...

Obviously my code doesn't work. And I'm tired of googling. can somebody please help me please?

Here is what I have up until now:

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

string lowercase(char inlower[]);

int main(void)
{
    string word = get_string("Type in a word: ");
    char inlower[strlen(word)];

    printf("You typed: %s\n", word);
}

string lowercase(string word)
{
    for (int i = 0, len = strlen(word); i < len; i  )
    {
        inlower[i] = tolower(word[i]);
        // printf("%c", inlower[i]);
    }
    return inlower[];
}

CodePudding user response:

You need to work on word and return word, not word[]. inlower is local to main and can't be used in lowercase, unless you pass it along as a parameter along with word.

Also note that you should cast the char in your char[] (string) to unsigned char before using it with tolower. If char is signed and the char[] contains negative values, calling tolower will cause undefined behavior.

#include <cs50.h>

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

string lowercase(string word)
{
    for (unsigned i = 0, len = strlen(word); i < len; i  )
    {
        word[i] = tolower((unsigned char) word[i]);
    }
    return word;
}

int main(void)
{
    string word = get_string("Type in a word: ");

    printf("You typed: %s\n", lowercase(word));
}

If you do want to put the lowercase word in inlower that you've declared in main, you also need to make it big enough for what you have in word. strlen(word) is one char short since every string must be terminated with a \0 char.

string lowercase(string inlower, string word)
{
    unsigned i = 0;
    for (unsigned len = strlen(word); i < len; i  )
    {
        inlower[i] = tolower((unsigned char) word[i]);
    }
    inlower[i] = '\0';
    return inlower;
}

int main(void)
{
    string word = get_string("Type in a word: ");

    char inlower[strlen(word)   1]; // correct size

    lowercase(inlower, word); // pass `inlower` in to `lowercase` too

    printf("You typed:    %s\n"
           "In lowercase: %s\n", word, inlower);
}

Alternative version without doing strlen inside lowercase too:

string lowercase(string inlower, string word)
{
    string dest = inlower;
    for(;*word;   word,   dest)
    {
        *dest = tolower((unsigned char) *word);
    }
    *dest = '\0';
    return inlower;
}

CodePudding user response:

try loop by char, use char 32 to lower.

in ASCII, A-Z any 32 = a-z

  • Related