1

I am new with strings in C++. I am just confused with the working of the code below (used to reverse a string).

std:: string    rev;

        for(int i=  str.size()-1;   i>=0;   --i)
        {
            rev.push_back(str[i]);  
        }

        std:: cout<<"   Reversed=   "<<rev<<endl;

The Problem is that the last character of a string is null character '\0'. So, when the loop runs for the first iteration, it should place a null character at the start of rev and one more thing, here the string rev may not be null terminated because '\0' is not assigned as the last character of string.

But when I execute the Program, it works fine. I know I am wrong while thinking all this. Can anyone explain the working please? I shall be glad and Thankful to you :)

HN Learner
  • 544
  • 7
  • 19

2 Answers2

4

The null terminator is not actually considered part of a std::string. It only comes into play when you call c_str(). So size() and length() do not include a terminator. And in fact you can put null characters into the middle of a std::string and everything will still work, except for c_str() (if your string may contain nulls you should use data() and size()).

John Zwinck
  • 239,568
  • 38
  • 324
  • 436
1

The '/0' operator is added automatically, so you are looping only till the character just before '/0'. It's always there basically, so you are not seeing any changes.

Dishonered
  • 8,449
  • 9
  • 37
  • 50