I am writing my own implementation of ToLower(char *str) in C. But i am getting segmentation fault in the function. The function which i wrote is :
void ToLower(
Although the name of your function ToLower()
suggests you are re-writing the ANSI C version of tolower()
, (i.e. changing one char from upper to lower case) your implementation suggests you really want an entire string to be changed. Perhaps the name StrToLower()
is what you are really intending? (i.e. change the entire string). If that is the case, the following code illustrates. (if you really want to re-write tolower()
, it should really be a different question, with a prototype similar to the C version, and changing only one char per call)
This answer assumes because of the tag "c" in your question, that you are not wanting the .NET version of String.ToLower()
(which DOES convert a string). If this is a wrong assumption, disregard my rants.
This method will work with a char *str="STRING";
, or with a constant string ("STRING"
) as an argument.
[Expanded] Include an implementation of ToLower, in case that is what OP really wanted.
#include
char * StrToLower(char *str) ;
int toLower(int chr);
int main(void)
{
char lowered[] = "UPPER to Lower";
sprintf(lowered, "%s",StrToLower(lowered));
printf("%s\n", lowered); //works with a variable buffer argument
lowered[0]=0;//clear the buffer
sprintf(lowered, "%s",StrToLower("UPPER to Lower"));
printf("%s\n", lowered); //also works with a literal string argument
getchar();//view results
return 0;
}
char * StrToLower(char *str)
{
char *pNew1 = str;
char *pNew2 = str;
if(str != NULL) //NULL ?
{
if(strlen(str) != 0) //"" ?
{
while(*pNew1)
{
*pNew2 = toLower(*pNew1);
++pNew2;
++pNew1;
}
*pNew2 = '\0';
return str;// return changed string
} // and prevent returning null to caller
}
return "";//Will never get here for non-null input argurment
}
int toLower(int chr)//touches only one character per call
{
return (chr >='A' && chr<='Z') ? (chr + 32) : (chr);
}
Results: (answering Roland's comment)