From 69ea1f7005d5dedd9f74ae913a255eb75f18b2ab Mon Sep 17 00:00:00 2001 From: Eric Teunis de Boone Date: Thu, 9 Jul 2020 23:47:59 +0200 Subject: [PATCH] Ex4.3: Optional Substring --- ex4.3/String.cc | 63 +++++++++++++++++++++++++++++++++++++++++++++++++ ex4.3/String.hh | 2 ++ ex4.3/main.cpp | 9 ++++++- 3 files changed, 73 insertions(+), 1 deletion(-) diff --git a/ex4.3/String.cc b/ex4.3/String.cc index 32b4e50..9566bf2 100644 --- a/ex4.3/String.cc +++ b/ex4.3/String.cc @@ -1,6 +1,7 @@ //String.cc #include "String.hh" +#include String operator+( const String& lhs, const String& rhs ) { String result(lhs); // Copy lhs into res with constructor result += rhs ; // Use operator+= function which is a member of the class @@ -28,3 +29,65 @@ String& String::operator+=( const String& a ) { return *this ; } +String& String::subString( int start, int stop ) { + /* + * Return a substring + * + * if stop is negative, interpret as len - stop + * if start is negative, set start = 0 + * + * if start > stop, return reversed string + */ + + bool reverse = 0; + int len = 0; + char * tmp; + + // Higher than Range + if ( start > _len ) { + start = _len ; + } + + if ( stop > _len ) { + stop = _len ; + } + + // Lower than Range + if ( start < 0 ) { + start = _len + start%_len ; + } + if ( stop < 0 ) { + stop = _len + stop%_len ; + } + + // Set length + len = stop - start; + + if ( start > stop ) { + // Make sure len is positive + len = -1 * len ; + reverse = 1; + } + + // allocate + tmp = new char[ len - 1]; + tmp[len] = '\0'; + + for ( int i = 0 ; i < len ; i++ ) + { + if ( reverse ) + { + tmp[i] = _s[ start - i ]; + } + else + { + tmp[i] = _s[ start + i ]; + } + } + + // make it a String again + String * result = new String(tmp); + delete tmp; + + return *result; +} diff --git a/ex4.3/String.hh b/ex4.3/String.hh index daf8c96..3bf5eed 100644 --- a/ex4.3/String.hh +++ b/ex4.3/String.hh @@ -12,6 +12,8 @@ public: String& operator=( const String& a ); String& operator+=( const String& a ); + String& subString( int start, int stop ); + operator const char* const() { return data(); } int length() const { return _len ; } diff --git a/ex4.3/main.cpp b/ex4.3/main.cpp index d4a4e2a..ca61fbe 100644 --- a/ex4.3/main.cpp +++ b/ex4.3/main.cpp @@ -1,6 +1,7 @@ +#include "String.hh" + #include #include -#include "String.hh" int main() { String str("Blubaloo"); @@ -32,4 +33,10 @@ int main() { String c("Almost Empty"); std::cout << "String '" << c.data() << "' is " << strlen(c) << " chars long." << std::endl; + + + // Substring + std::cout << "First five characters: " << c.subString(0, 5) << std::endl; + std::cout << "First five characters reversed: " << c.subString(5, 0) << std::endl; + std::cout << "Last five characters: " << c.subString(-5, -1) << std::endl; }