diff options
author | Nicolas Catania <niko@google.com> | 2010-01-28 16:48:34 -0800 |
---|---|---|
committer | Nicolas Catania <niko@google.com> | 2010-01-30 16:59:41 -0800 |
commit | 74a6fdea77d52a17be4bc38831fe02a31cefbf34 (patch) | |
tree | 4ee780faead236dddaa2d0eda7b3e5febbcac138 | |
parent | 2f8be091d59666a33e3fd11fca1ce71f0a90edbc (diff) | |
download | astl-74a6fdea77d52a17be4bc38831fe02a31cefbf34.tar.gz |
Added the 'at' method to string.
-rw-r--r-- | include/string | 4 | ||||
-rw-r--r-- | src/string.cpp | 23 | ||||
-rw-r--r-- | tests/test_string.cpp | 8 |
3 files changed, 35 insertions, 0 deletions
diff --git a/include/string b/include/string index 8e1ebbe..7c2f474 100644 --- a/include/string +++ b/include/string @@ -193,6 +193,10 @@ class string // @return a reference to the char. char& operator[](const size_type pos); + // 'at' is similar to operator[] except that it does check bounds. + const char& at(const size_type pos) const; + char& at(const size_type pos); + // Assignments. string& operator=(const string& str) { return assign(str); } string& operator=(const char* str) { return assign(str); } diff --git a/src/string.cpp b/src/string.cpp index e1c4cf9..d0361e6 100644 --- a/src/string.cpp +++ b/src/string.cpp @@ -39,6 +39,9 @@ namespace { char kEmptyString[1] = { '\0' }; +// Dummy char used in the 'at' accessor when the index is out of +// range. +char sDummy; } namespace std { @@ -446,6 +449,26 @@ char& string::operator[](const size_type pos) return mData[pos]; } +const char& string::at(const size_type pos) const +{ + if (pos < mLength) { + return mData[pos]; + } else { + sDummy = 'X'; + return sDummy; + } +} + +char& string::at(const size_type pos) +{ + if (pos < mLength) { + return mData[pos]; + } else { + sDummy = 'X'; + return sDummy; + } +} + string& string::assign(const string& str) { clear(); diff --git a/tests/test_string.cpp b/tests/test_string.cpp index 60c02aa..337d879 100644 --- a/tests/test_string.cpp +++ b/tests/test_string.cpp @@ -542,6 +542,14 @@ bool testAccessor() str05.reserve(100); str05[99] = 'a'; + // 'at' + EXPECT_TRUE(str01.at(0) == 'E'); + EXPECT_TRUE(str01.at(7) == 'S'); + EXPECT_TRUE(str01.at(8) == 'X'); // 'X' is the dummy value returned. + + str01.at(1) = 'A'; + str01.at(6) = 'K'; + EXPECT_TRUE(str01 == "EArmarKS"); return true; } |