need help on string and char

hello, i wanna tolower a string and return it, but do not change the original value.

1
2
3
4
5
6
7
8
9
10
string tolower(string fStr)
{
   char strings[fStr.size() + 1];//this is the temp char to store string
   for(int i = 0; i < fStr.size(); i++)
      strings[i] = tolower(fStr[i]);
   cout << strings << endl;
   return strings;
   //however, the output contains a lot of unknow things
   //but i have already limit the size of array in the declaration
}

for example:
original: Before
correct: before
but now: before�?rP�������H

how can i change?
You need a null terminator at the end of your character array: '\0'.

Also, string::size() returns the size of the string in characters, including the null terminator character. Perhaps you should consider string::length(), which does not include the null terminator.
There are a lot of problems of your code
(1)char strings[fStr.size() + 1] //array size of C style can't decide the size at run time(std::string can)
(2)string tolower(string fStr) //your return type is std::string but not char
(2)you don't need to pass string fStr as a copy

example
1
2
3
4
5
6
7
8
string tolower(string const& fStr)
{  
  std::string temp(fStr); //copy the contents of origin to temp
  //do what you want on temp
  //there are a lot of ways to do this, like while loop, for loop, or the algorithms of stl
  //like std::transform or std::for_each, if your compiler support lambda
 //you could generate the functor by a neat way
}


if you don't want to iterate the string by iterator but by something like
 
for(size_t i = 0; i != .....)

remember to set the i as
 
for(std::string::size_type i = 0; i != s.size(); ++i)



string::size() returns the size of the string in characters, including the null terminator character.

according to http://www.cplusplus.com/reference/string/string/length/
string::length is an alias of string::size, returning both the exact same value(without '\0')
Last edited on
Topic archived. No new replies allowed.