String length function


when i input “hello” , the program returns 5 as output, why wont it be 6 , as ‘\0’ character is automatically added at the end?

Hi @chahatkumar
The length() or the size() (Both are same) return the length of the string .
The ‘\0’ character is not counted for it.
Infact the internal implementation of string class doesn’t even require it to put a ‘\0’ character at the end. So in most cases , the ‘\0’ character is not even there.

Also if you were using the character arrays and call the strlen( ) function to get its length , even though it has a ‘\0’ character at the end , strlen( ) function doesn’t count it either.

I tried a little something with your code . Take a look at this and hope this clears your doubt.

This is kind of like proof by contradiction.

okay thanks
but the output for “hello” now is “helo”
why does it skips one ‘l’,instead of putting some garbage value at that place?

When I ran the code , it showed the output as “he lo”. It gave a space.
And thats the point. The character at the s[n] location could be any random character.It could be some digit , symbol , alphabet letter or any other such random character. In my case , there was a space at the s[n] location, it seems in your case , it picked up some whitespace character which is skipped while printing. There’s 1/256 chance that the s[n] character could be the ‘\0’ as well. Its just random.

The main point is that the string class does not need the ‘\0’ at the end and the length() and the size() function dont count it either.

okay thankyouu :slight_smile: