Monday, May 24, 2010

How do I copy a string and make it all lower case inside a function and return this new string in C?

I know it should go something like this:





*char blah(char *str){


-create a char *str2 using malloc


-initialize str2 using strcopy


-create a for loop to go char by char in the string and


convert using tolower()


-return the new string


}





I'm having problems with the actual coding in that I'm new and not entirely sure what how to initialize the str2 or actually implement the loop. Please help.

How do I copy a string and make it all lower case inside a function and return this new string in C?
string StringToLower(string strToConvert)


{//change each element of the string to lower case


for(unsigned int i=0;i%26lt;strToConvert.length();i++)


{


strToConvert[i] = tolower(strToConvert[i]);


}


return strToConvert;//return the converted string


}
Reply:there's no need to copy it once with strcpy and then write over it again with your loop.. do it all at once--





// size = strlen(str)


// malloc "size+1" bytes (edited, dvari is correct :-) )


// loop until end of string


for (i=0; i %26lt; size; ++i)


{


strOutput[i] = tolower(str[i]); // save


}


str[size] = '\0'; // remember to zero terminate
Reply:Either example is fine. Just remember to allocate "size + 1" (rather than "size") bytes to allow space for the null terminator.

daisy

No comments:

Post a Comment