Quick question about strings

This is a discussion on Quick question about strings within the C++ Programming forums, part of the General Programming Boards category; I was just wondering if you could use an integer for the character number in a string.
For example:
Code:
...

"Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
-Christopher Hitchens

You could of course also use a for loop or iterators. And using at() as [code][/code] suggested checks to make sure you are using a valid index and throws an exception if you are outside the string bounds.

const char *'s returned from c_str() are required to be null terminated. This makes it likely that the string will keep it's data as a null terminated contigous memory, but it's not required. The null could be inserted during the call to c_str().

If STL strings werenīt null terminated how is it possible that c_str() that returns const char * can be used in c-functions (not advisable) e.i strlen? But I must admit that jlou solution is better (safer).

According to Josuttis (The C++ Standard Library), if you use the constant version of basic_string::operator[] and you pass in the length of the string (which would be one past the last character), then the value that is generated by the default constructor of the character type is returned. In the case of string (which is really basic_string<char>), the default constructor for char creates the null character, '\0'.

So, for the constant version of operator[], it is ok to access the null character at the end of the string.

However, strings can have embedded nulls, so if you didn't know the value of the string beforehand, and you looped through until you got a null character, you might not get the entire string before finding a null.

Also, if you use the non-constant version of operator[] or if you use at(), then if you do this: str[str.length()], you will get undefined behavior and if you do this: str.at(str.length()), it should throw an exception.

Given all that, there is nothing that says the implementation has to store the string with a terminating null. Only that it will return a null character if you use the constant version of operator[] on the index one past the last character. I'm not sure how it would get c_str() to work efficiently without doing so, but I also don't care unless I am doing some extremely time critical application and I need to know the implementation details of my standard library.