Actaeonis
Actaeonis

Reputation: 159

Converting a C-String to all lower

I'm trying to convert a C-String to all lower case wihout the use of tolower from ctype.h . Hower my code does not seem to work: I'm receiving a runtime error. What I'm trying to do is changing the ASCII value of the capitalized letters bij 'a' - 'A' which should convert those values to the ones for lower case as far as I'm aware.

#include <stdio.h>
void to_lower(char* k) {
    char * temp = k;
    while(*temp != 0) {
        if(*temp > 'A' && *temp < 'Z') {
            *temp += ('a' - 'A');
        }
        temp++;
    }
}

int main() {
    char * s = "ThiS Is AN eXaMpLe";
    to_lower(s);
    printf("%s",s);
}

Upvotes: 0

Views: 158

Answers (3)

luser droog
luser droog

Reputation: 19504

Even if you don't use the existing standard library function, it may still be useful to follow its interface. tolower converts an individual character. Applying this function to a string can be written as a de-coupled function.

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

int to_lower (int c) {
    if (strchr("ABCDEFGHIJKLMNOPQRSTUVWXYZ", c))
        c = c - 'A' + 'a';
    return c;         
}

void mapstring (char *str, int (*f)(int)) {
    for (; *str; str++)
        *str = f(*str);
}

int main() {
    char s[] = "THIS IS MY STRING";

    mapstring(s, to_lower);
    printf("%s\n", s); 
    return 0;
}

Upvotes: 1

Lee Daniel Crocker
Lee Daniel Crocker

Reputation: 13196

Two problems that I can see immediately: (1) char *s = "This..." creates a non-writable string. You need to use a character array and copy a string into it. (2) if (*temp > 'A' && *temp < 'Z') skips A and Z. You need >= and <=.

Upvotes: 0

tux3
tux3

Reputation: 7330

Two errors.

This code won't convert A and Z to lowercase :

if(*temp > 'A' && *temp < 'Z') {

Use >= and <= instead.

And it's not legal to try to modify a string literal ! Arrays can be modified, string literals can't.

Change that char * s = "ThiS Is AN eXaMpLe"; to char s[] = "ThiS Is AN eXaMpLe";

Upvotes: 9

Related Questions