1
0
Fork 0

Ex4.3: Optional Substring

This commit is contained in:
Eric Teunis de Boone 2020-07-09 23:47:59 +02:00
parent c6e48cf47c
commit 69ea1f7005
3 changed files with 73 additions and 1 deletions

View File

@ -1,6 +1,7 @@
//String.cc
#include "String.hh"
#include <iostream>
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;
}

View File

@ -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 ; }

View File

@ -1,6 +1,7 @@
#include "String.hh"
#include <iostream>
#include <cstring>
#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;
}