I was taught string::at
in school, but by exploring the string library I saw string::operator[]
, which I was never shown before.
I'm now using operator[]
and haven't used at
since, but what is the difference?
Here is some sample code:
std::string foo = "my redundant string has some text";
std::cout << foo[5];
std::cout << foo.at(5);
They are essentially the same in terms of output, but are there some subtle differences I'm not aware of?
There is no functionality difference between string and std::string because they're the same type.
Differences between std::string and String Pavan. std::string is the string class from the standard C++ library. String is some other string class from some other library. It's hard to say from which library, because there are many different libraries that have their own class called String.
std::string class in C++ C++ has in its definition a way to represent a sequence of characters as an object of the class. This class is called std:: string. String class stores the characters as a sequence of bytes with the functionality of allowing access to the single-byte character.
at() is a member function in C++. s.at() returns the letter at position i in the string. But if the position is not in the range, it throws an exception.
Yes, there is one major difference: using .at()
does a range check on index passed and throws an exception if it's over the end of the string while operator[]
just brings undefined behavior in that situation.
at
does bounds checking, exception of type std::out_of_range
will be thrown on invalid access.
operator[]
does NOT check bounds and thus can be dangerous if you try to access beyond the bounds of the string. It is a little faster than at
though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With