diff options
-rw-r--r-- | include/string | 4 | ||||
-rw-r--r-- | src/string.cpp | 9 | ||||
-rw-r--r-- | tests/test_string.cpp | 34 |
3 files changed, 44 insertions, 3 deletions
diff --git a/include/string b/include/string index 0f6de29..bcf13d8 100644 --- a/include/string +++ b/include/string @@ -263,6 +263,10 @@ class string iterator end() {return iterator(mData + mLength);} const_iterator end() const {return const_iterator(mData + mLength);} + // @return the substring [pos, pos + n]. + // Requires pos <= size(). If n > size() - pos, size() - pos is used. + string substr(size_type pos = 0, size_type n = npos) const; + private: bool SafeMalloc(size_type n); void SafeRealloc(size_type n); diff --git a/src/string.cpp b/src/string.cpp index 05f2634..b67e732 100644 --- a/src/string.cpp +++ b/src/string.cpp @@ -185,8 +185,11 @@ string::string(const string& str) string::string(const string& str, size_type pos, size_type n) { - if (pos < str.mLength && n <= (str.mLength - pos)) + if (pos < str.mLength) { + if (n > (str.mLength - pos)) { + n = str.mLength - pos; + } Constructor(str.mData + pos , n); } else @@ -553,6 +556,10 @@ string::size_type string::find(const value_type *str, size_type pos) const return static_cast<size_type>(delta); } +string string::substr(size_type pos, size_type n) const { + return string(*this, pos, n); +} + ostream& operator<<(ostream& os, const string& str) { return os.write_formatted(str.data(), str.size()); } diff --git a/tests/test_string.cpp b/tests/test_string.cpp index d06f88e..100b23b 100644 --- a/tests/test_string.cpp +++ b/tests/test_string.cpp @@ -188,8 +188,8 @@ bool testConstructorInvalidValues() string str04(str01, -1, 0); // invalid index EXPECT_TRUE(str04.c_str() == empty.c_str()); - string str05(str01, 0, 17); // invalid length - EXPECT_TRUE(str05.c_str() == empty.c_str()); + string str05(str01, 0, 17); // invalid length -> clamped + EXPECT_TRUE(str05 == str01); string str06(str01, 17); // invalid index EXPECT_TRUE(str06.c_str() == empty.c_str()); @@ -914,6 +914,35 @@ bool testForwardIterator() return true; } +bool testSubstr() { + { + string s; + string res = s.substr(10, 1); + EXPECT_TRUE(res.empty()); + } + { + string s = "pandora radio"; + string res = s.substr(string::npos, 1); + EXPECT_TRUE(res.empty()); + } + { + string s = "pandora radio"; + string res = s.substr(5, 1000); + EXPECT_TRUE(res == "ra radio"); + } + { + string s = "pandora radio"; + string res = s.substr(5, 0); + EXPECT_TRUE(res.empty()); + } + { + string s = "pandora radio"; + string res = s.substr(5, 5); + EXPECT_TRUE(res == "ra ra"); + } + return true; +} + } // namespace android int main(int argc, char **argv) @@ -941,5 +970,6 @@ int main(int argc, char **argv) FAIL_UNLESS(testErase); FAIL_UNLESS(testConstIterator); FAIL_UNLESS(testForwardIterator); + FAIL_UNLESS(testSubstr); return kPassed; } |