A strtolower function in C
Whilst reading K&R today, I came across an example function in written in C, which converts ASCII uppercase characters to their lowercase equivalents. It sounded like a useful function, so I closed the book after a quick glance and decided to have a crack it myself. I decided to name it strtolower(), like how it is in PHP (though of course usually in PHP I use a Unicode aware function for string length).
I'm also aware there is a strlen() function in C, but because I have yet to read about it in the book, I decided to use the old loop through char by char looking for the null char. Works for me :)
#include <stdio.h>
void strtolower(char str[]);
int main () {
char stringy[] = "Hello C!";
strtolower(stringy);
printf("%s\n", stringy);
return 0;
}
void strtolower(char str[]) {
int i;
for (i = 0; str[i] != '\0'; ++i) {
if (str[i] >= 'A' && str[i] <= 'Z') {
str[i] = str[i] + 'a' - 'A';
}
}
}It pretty much works the same as the PHP function, except the string is pass by reference as strings can't be passed by value or returned (I'm pretty sure at least). If you are wondering about the a-A part, have a look at the ASCII character set and note the fixed distance apart from lowercase to uppercase chars.
Also, I realise this stuff is pretty basic, but by writing it down and writing a post about it, I hope it will help my learning experience. Also, if you are like me and learning C after spending a lot of time in high level interpreted languages, you may find this function (and associated posts) useful for learning.
Comments
Alexander Dickson
Posted on Monday, 16th August 2010 @ 9:29am.@Brian Thanks for the input. I also realised I didn't need a separate loop to calculate the length first, when I could just check for the null char in the condition of my main loop.
Brian
Posted on Monday, 16th August 2010 @ 9:22am.You could get away with just doing a single pass by using the str pointer.
Leave a Comment
Note: Your comment may require approval before it is posted to the site.