SlideShare une entreprise Scribd logo
1  sur  9
#include "String.hpp"
#include "../Functions/functions.hpp"
// O(1)
String::String() {
// Allocate space.
array = new char[1];
// Add the null.
array[0] = '0';
// Adjust private variables.
_capacity = 0;
_size = 0;
}
// O(1)
String::String(char c) {
// Allocate space.
array = new char[2];
// Add the character and the null.
array[0] = c;
array[1] = '0';
// Adjust private variables.
_capacity = 1;
_size = 1;
}
// O(n)
String::String(char* str) {
// Get the length of the incoming string.
int length = 0;
while (str[length])
++length;
// Allocate space for the string plus a null.
array = new char[length + 1];
// Fill our array up, including the null.
for (int i = 0; i <= length; ++i)
array[i] = str[i];
// Adjust private variables.
_capacity = length;
_size = length;
}
// O(1)
String::~String() {
delete[] array;
}
// O(n)
char String::at(int index) const {
// If our index is negative, or beyond the size of our array, we
cannot return
// anything.
return (index < 0 || (unsigned int)index >= size()) ? throw
"Index"
: array[index];
}
void String::clear() {
for (unsigned int i = 0; i < _capacity; ++i)
array[i] = '0';
_size = 0;
}
// O(n)
unsigned int String::size() const {
return _size;
}
// O(1)
bool String::empty() const {
return !this->array[0];
}
// O(1)
unsigned int String::capacity() const {
return this->_capacity;
}
// O(n)
void String::reserve(unsigned int n) {
if (!n)
return;
// Make a new array.
char* _array = new char[_capacity + n + 1]();
// Fill it up.
int length = this->size();
for (int i = 0; i <= length; ++i)
_array[i] = array[i];
// Remove old memory.
delete[] array;
// Save new memory.
array = _array;
// Adjust private variables.
_capacity += n;
return;
}
// O(n)
void String::insert(char c, int index) {
// Prepend and append as easy cases.
if (index <= 0)
prepend(c);
else if ((unsigned int)index >= size())
append(c);
else {
// Increase capacity, if needed.
if (this->size() == this->_capacity) {
this->reserve(this->size() * 2);
}
// Move all elements after index over.
for (int i = this->size() + 1; i >= index; --i)
array[i] = array[i - 1];
// Insert our new character.
array[index] = c;
_size++;
}
return;
}
// O(n)
void String::erase(char c) {
// Create a new array.
char* _array = new char[_capacity + 1];
// Copy all non-erased characters to the new array.
int length = size();
for (int i = 0, j = 0; i <= length; ++i) {
if (array[i] != c)
_array[j++] = array[i];
else
_size--;
}
// Remove the old array.
delete[] array;
array = _array;
return;
}
// O(n)
void String::remove(int index) {
// Copy all characters to the left, overwriting index.
int length = this->size();
for (int i = index; i < length; ++i)
array[i] = array[i + 1];
_size--;
return;
}
// O(1) Amortized Cost due to doubling.
// More info:
// https://www.interviewcake.com/concept/java/dynamic-array-
amortized-analysis
void String::append(char c) {
unsigned int length = size();
if (length >= this->capacity()) {
this->reserve((length + 1) * 2);
}
array[length] = c;
array[length + 1] = 0;
_size++;
return;
}
// O(n)
void String::prepend(char c) {
unsigned int length = size();
if (length >= this->capacity()) {
this->reserve((length + 1) * 2);
}
for (int i = length + 1; i > 0; --i)
array[i] = array[i - 1];
array[0] = c;
_size++;
return;
}
// O(n)
bool String::compare(char* str) const {
int length = size();
// Compare all the way up to the null.
for (int i = 0; i <= length; ++i) {
if (str[i] != array[i])
return false;
}
return true;
}
// O(n)
bool String::compare(const String& str) const {
return this->compare(str.array);
}
// O(n)
void String::concatenate(char* str) {
// Get our lengths.
unsigned int strlen = 0, length = size();
while (str[strlen])
++strlen;
// Reserve the space
if (length + strlen > this->_capacity) {
this->reserve(strlen);
}
// Copy things over.
for (unsigned int i = length, j = 0; i <= length + strlen; ++i,
++j) {
this->array[i] = str[j];
}
_size += strlen;
return;
}
// O(n)
void String::concatenate(String& str) {
this->concatenate(str.array);
return;
}
// O(n)
inline bool exact_match(char* a, char* b) {
return (!b[0]) ? true : a[0] == b[0] && exact_match(a + 1, b +
1);
}
// O(n^2)
unsigned int String::find(char* str, int start) const {
unsigned int i, length;
for (i = start, length = size(); i < length; ++i) {
if (exact_match(this->array + i, str))
return i;
}
return i;
}
// O(n)
unsigned int String::find(char c, int start) const {
unsigned int i, length;
for (i = start, length = size(); i < length; ++i)
if (array[i] == c)
return i;
return i;
}
// O(n^2)
unsigned int String::find(String& str, int start) const {
return this->find(str.array, start);
}
// O(n)
void String::reverse() {
int length = size() - 1;
for (int i = 0; i < length / 2; ++i) {
array[i] ^= array[length - i];
array[length - i] ^= array[i];
array[i] ^= array[length - i];
}
return;
}
// O(n)
void String::shift(int n) {
int length = size();
for (int i = 0; i < length; ++i) {
array[i] = array[i] + n % 255;
if (!array[i])
++array[i];
}
return;
}
// O(n)
int String::toInt() const {
return stringtoint(this->array);
}
// O(n) since append is O(1) amortized.
String String::substr(int start, int end) const {
String ret;
for (int i = start; i < end; ++i)
ret.append(array[i]);
return ret;
}
void String::print(std::ostream& oss) const {
for (int i = 0; array[i]; ++i)
oss << array[i];
}
std::ostream& operator<<(std::ostream& oss, const String& str)
{
str.print(oss);
return oss;
}
char String::pop_back() {
if (empty())
throw "Nothing to pop";
char c = array[_size - 1];
array[_size--] = '0';
return c;
}

Contenu connexe

Similaire à #include String.hpp#include ..Functionsfunctions.hpp.docx

a) Write the recursive function in C++ to sort a set of data using M.pdf
a) Write the recursive function in C++ to sort a set of data using M.pdfa) Write the recursive function in C++ to sort a set of data using M.pdf
a) Write the recursive function in C++ to sort a set of data using M.pdf
nageswara1958
 
This is a c++ binary search program I worked so far but still cant g.pdf
This is a c++ binary search program I worked so far but still cant g.pdfThis is a c++ binary search program I worked so far but still cant g.pdf
This is a c++ binary search program I worked so far but still cant g.pdf
kostikjaylonshaewe47
 
Lecture 15_Strings and Dynamic Memory Allocation.pptx
Lecture 15_Strings and  Dynamic Memory Allocation.pptxLecture 15_Strings and  Dynamic Memory Allocation.pptx
Lecture 15_Strings and Dynamic Memory Allocation.pptx
JawadTanvir
 
Data StructuresPLEASE USING THIS C++ PROGRAM BELOW, I NEED HEL.pdf
Data StructuresPLEASE USING THIS C++ PROGRAM BELOW, I NEED HEL.pdfData StructuresPLEASE USING THIS C++ PROGRAM BELOW, I NEED HEL.pdf
Data StructuresPLEASE USING THIS C++ PROGRAM BELOW, I NEED HEL.pdf
rozakashif85
 
Can anyone fix this code, I use Visual StudiosThe Errors im getti.pdf
Can anyone fix this code, I use Visual StudiosThe Errors im getti.pdfCan anyone fix this code, I use Visual StudiosThe Errors im getti.pdf
Can anyone fix this code, I use Visual StudiosThe Errors im getti.pdf
arjunhassan8
 

Similaire à #include String.hpp#include ..Functionsfunctions.hpp.docx (20)

a) Write the recursive function in C++ to sort a set of data using M.pdf
a) Write the recursive function in C++ to sort a set of data using M.pdfa) Write the recursive function in C++ to sort a set of data using M.pdf
a) Write the recursive function in C++ to sort a set of data using M.pdf
 
This is a c++ binary search program I worked so far but still cant g.pdf
This is a c++ binary search program I worked so far but still cant g.pdfThis is a c++ binary search program I worked so far but still cant g.pdf
This is a c++ binary search program I worked so far but still cant g.pdf
 
Lecture 15_Strings and Dynamic Memory Allocation.pptx
Lecture 15_Strings and  Dynamic Memory Allocation.pptxLecture 15_Strings and  Dynamic Memory Allocation.pptx
Lecture 15_Strings and Dynamic Memory Allocation.pptx
 
2- Dimensional Arrays
2- Dimensional Arrays2- Dimensional Arrays
2- Dimensional Arrays
 
The java language cheat sheet
The java language cheat sheetThe java language cheat sheet
The java language cheat sheet
 
C++11 - STL Additions
C++11 - STL AdditionsC++11 - STL Additions
C++11 - STL Additions
 
Data structure array
Data structure  arrayData structure  array
Data structure array
 
Unit 2
Unit 2Unit 2
Unit 2
 
Unit 3 arrays and_string
Unit 3 arrays and_stringUnit 3 arrays and_string
Unit 3 arrays and_string
 
DS Code (CWH).docx
DS Code (CWH).docxDS Code (CWH).docx
DS Code (CWH).docx
 
Java cheatsheet
Java cheatsheetJava cheatsheet
Java cheatsheet
 
Data StructuresPLEASE USING THIS C++ PROGRAM BELOW, I NEED HEL.pdf
Data StructuresPLEASE USING THIS C++ PROGRAM BELOW, I NEED HEL.pdfData StructuresPLEASE USING THIS C++ PROGRAM BELOW, I NEED HEL.pdf
Data StructuresPLEASE USING THIS C++ PROGRAM BELOW, I NEED HEL.pdf
 
Dynamic Objects,Pointer to function,Array & Pointer,Character String Processing
Dynamic Objects,Pointer to function,Array & Pointer,Character String ProcessingDynamic Objects,Pointer to function,Array & Pointer,Character String Processing
Dynamic Objects,Pointer to function,Array & Pointer,Character String Processing
 
Arrays
ArraysArrays
Arrays
 
C (PPS)Programming for problem solving.pptx
C (PPS)Programming for problem solving.pptxC (PPS)Programming for problem solving.pptx
C (PPS)Programming for problem solving.pptx
 
Data Structures Using C Practical File
Data Structures Using C Practical File Data Structures Using C Practical File
Data Structures Using C Practical File
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
VIT351 Software Development VI Unit2
VIT351 Software Development VI Unit2VIT351 Software Development VI Unit2
VIT351 Software Development VI Unit2
 
Pointers and arrays
Pointers and arraysPointers and arrays
Pointers and arrays
 
Can anyone fix this code, I use Visual StudiosThe Errors im getti.pdf
Can anyone fix this code, I use Visual StudiosThe Errors im getti.pdfCan anyone fix this code, I use Visual StudiosThe Errors im getti.pdf
Can anyone fix this code, I use Visual StudiosThe Errors im getti.pdf
 

Plus de gertrudebellgrove

-I am unable to accept emailed exams or late exams. No exception.docx
-I am unable to accept emailed exams or late exams. No exception.docx-I am unable to accept emailed exams or late exams. No exception.docx
-I am unable to accept emailed exams or late exams. No exception.docx
gertrudebellgrove
 
-1st play name is READY STEADY YETI GO-2nd play name is INTO .docx
-1st play name is READY STEADY YETI GO-2nd play name is INTO .docx-1st play name is READY STEADY YETI GO-2nd play name is INTO .docx
-1st play name is READY STEADY YETI GO-2nd play name is INTO .docx
gertrudebellgrove
 
. 1. Rutter and Sroufe identified _____________ as one of three impo.docx
. 1. Rutter and Sroufe identified _____________ as one of three impo.docx. 1. Rutter and Sroufe identified _____________ as one of three impo.docx
. 1. Rutter and Sroufe identified _____________ as one of three impo.docx
gertrudebellgrove
 
- FIRST EXAM SPRING 20201. Describe how the view of operations.docx
- FIRST EXAM SPRING 20201. Describe how the view of operations.docx- FIRST EXAM SPRING 20201. Describe how the view of operations.docx
- FIRST EXAM SPRING 20201. Describe how the view of operations.docx
gertrudebellgrove
 
- 2 -Section CPlease write your essay in the blue book.docx
- 2 -Section CPlease write your essay in the blue book.docx- 2 -Section CPlease write your essay in the blue book.docx
- 2 -Section CPlease write your essay in the blue book.docx
gertrudebellgrove
 

Plus de gertrudebellgrove (20)

-I am unable to accept emailed exams or late exams. No exception.docx
-I am unable to accept emailed exams or late exams. No exception.docx-I am unable to accept emailed exams or late exams. No exception.docx
-I am unable to accept emailed exams or late exams. No exception.docx
 
-delineate characteristics, prevalence of  exceptionality-evalua.docx
-delineate characteristics, prevalence of  exceptionality-evalua.docx-delineate characteristics, prevalence of  exceptionality-evalua.docx
-delineate characteristics, prevalence of  exceptionality-evalua.docx
 
-1st play name is READY STEADY YETI GO-2nd play name is INTO .docx
-1st play name is READY STEADY YETI GO-2nd play name is INTO .docx-1st play name is READY STEADY YETI GO-2nd play name is INTO .docx
-1st play name is READY STEADY YETI GO-2nd play name is INTO .docx
 
-6th-Edition-Template-without-Abstract.dotWhat are Heuristics .docx
-6th-Edition-Template-without-Abstract.dotWhat are Heuristics .docx-6th-Edition-Template-without-Abstract.dotWhat are Heuristics .docx
-6th-Edition-Template-without-Abstract.dotWhat are Heuristics .docx
 
- write one 5-7 page paper about All forms of Euthanasia are moral..docx
- write one 5-7 page paper about All forms of Euthanasia are moral..docx- write one 5-7 page paper about All forms of Euthanasia are moral..docx
- write one 5-7 page paper about All forms of Euthanasia are moral..docx
 
-1st Play name is BERNHARDTHAMLET -2nd Play name is READY ST.docx
-1st Play name is BERNHARDTHAMLET -2nd Play name is READY ST.docx-1st Play name is BERNHARDTHAMLET -2nd Play name is READY ST.docx
-1st Play name is BERNHARDTHAMLET -2nd Play name is READY ST.docx
 
. 1. Rutter and Sroufe identified _____________ as one of three impo.docx
. 1. Rutter and Sroufe identified _____________ as one of three impo.docx. 1. Rutter and Sroufe identified _____________ as one of three impo.docx
. 1. Rutter and Sroufe identified _____________ as one of three impo.docx
 
-Prior to the Civil War, how did the (dominant) discourse over the U.docx
-Prior to the Civil War, how did the (dominant) discourse over the U.docx-Prior to the Civil War, how did the (dominant) discourse over the U.docx
-Prior to the Civil War, how did the (dominant) discourse over the U.docx
 
- Using the definition Awareness of sensation and perception to ex.docx
- Using the definition Awareness of sensation and perception to ex.docx- Using the definition Awareness of sensation and perception to ex.docx
- Using the definition Awareness of sensation and perception to ex.docx
 
- should include an introduction to the environmental issue and its .docx
- should include an introduction to the environmental issue and its .docx- should include an introduction to the environmental issue and its .docx
- should include an introduction to the environmental issue and its .docx
 
- FIRST EXAM SPRING 20201. Describe how the view of operations.docx
- FIRST EXAM SPRING 20201. Describe how the view of operations.docx- FIRST EXAM SPRING 20201. Describe how the view of operations.docx
- FIRST EXAM SPRING 20201. Describe how the view of operations.docx
 
- Considering the concepts, examples and learning from the v.docx
- Considering the concepts, examples and learning from the v.docx- Considering the concepts, examples and learning from the v.docx
- Considering the concepts, examples and learning from the v.docx
 
- Discuss why a computer incident response team (CIRT) plan is neede.docx
- Discuss why a computer incident response team (CIRT) plan is neede.docx- Discuss why a computer incident response team (CIRT) plan is neede.docx
- Discuss why a computer incident response team (CIRT) plan is neede.docx
 
- Discuss why a computer incident response team (CIRT) plan is n.docx
- Discuss why a computer incident response team (CIRT) plan is n.docx- Discuss why a computer incident response team (CIRT) plan is n.docx
- Discuss why a computer incident response team (CIRT) plan is n.docx
 
- 2 -Section CPlease write your essay in the blue book.docx
- 2 -Section CPlease write your essay in the blue book.docx- 2 -Section CPlease write your essay in the blue book.docx
- 2 -Section CPlease write your essay in the blue book.docx
 
- Confidence intervals for a population mean, standard deviation kno.docx
- Confidence intervals for a population mean, standard deviation kno.docx- Confidence intervals for a population mean, standard deviation kno.docx
- Confidence intervals for a population mean, standard deviation kno.docx
 
) Create a new thread. As indicated above, select  two tools describ.docx
) Create a new thread. As indicated above, select  two tools describ.docx) Create a new thread. As indicated above, select  two tools describ.docx
) Create a new thread. As indicated above, select  two tools describ.docx
 
(Write 3 to 4 sentences per question)  1. Describe one way y.docx
(Write 3 to 4 sentences per question)  1. Describe one way y.docx(Write 3 to 4 sentences per question)  1. Describe one way y.docx
(Write 3 to 4 sentences per question)  1. Describe one way y.docx
 
( America and Venezuela) this is a ppt. groups assignment. Below is .docx
( America and Venezuela) this is a ppt. groups assignment. Below is .docx( America and Venezuela) this is a ppt. groups assignment. Below is .docx
( America and Venezuela) this is a ppt. groups assignment. Below is .docx
 
++ 2 PAGES++Topic Make a bill to legalize all felon has the rig.docx
++ 2 PAGES++Topic Make a bill to legalize all felon has the rig.docx++ 2 PAGES++Topic Make a bill to legalize all felon has the rig.docx
++ 2 PAGES++Topic Make a bill to legalize all felon has the rig.docx
 

Dernier

Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
PECB
 
Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.
MateoGardella
 

Dernier (20)

This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.
 

#include String.hpp#include ..Functionsfunctions.hpp.docx

  • 1. #include "String.hpp" #include "../Functions/functions.hpp" // O(1) String::String() { // Allocate space. array = new char[1]; // Add the null. array[0] = '0'; // Adjust private variables. _capacity = 0; _size = 0; } // O(1) String::String(char c) { // Allocate space. array = new char[2]; // Add the character and the null. array[0] = c; array[1] = '0'; // Adjust private variables. _capacity = 1; _size = 1; } // O(n) String::String(char* str) { // Get the length of the incoming string. int length = 0;
  • 2. while (str[length]) ++length; // Allocate space for the string plus a null. array = new char[length + 1]; // Fill our array up, including the null. for (int i = 0; i <= length; ++i) array[i] = str[i]; // Adjust private variables. _capacity = length; _size = length; } // O(1) String::~String() { delete[] array; } // O(n) char String::at(int index) const { // If our index is negative, or beyond the size of our array, we cannot return // anything. return (index < 0 || (unsigned int)index >= size()) ? throw "Index" : array[index]; } void String::clear() { for (unsigned int i = 0; i < _capacity; ++i) array[i] = '0'; _size = 0; }
  • 3. // O(n) unsigned int String::size() const { return _size; } // O(1) bool String::empty() const { return !this->array[0]; } // O(1) unsigned int String::capacity() const { return this->_capacity; } // O(n) void String::reserve(unsigned int n) { if (!n) return; // Make a new array. char* _array = new char[_capacity + n + 1](); // Fill it up. int length = this->size(); for (int i = 0; i <= length; ++i) _array[i] = array[i]; // Remove old memory. delete[] array; // Save new memory. array = _array; // Adjust private variables.
  • 4. _capacity += n; return; } // O(n) void String::insert(char c, int index) { // Prepend and append as easy cases. if (index <= 0) prepend(c); else if ((unsigned int)index >= size()) append(c); else { // Increase capacity, if needed. if (this->size() == this->_capacity) { this->reserve(this->size() * 2); } // Move all elements after index over. for (int i = this->size() + 1; i >= index; --i) array[i] = array[i - 1]; // Insert our new character. array[index] = c; _size++; } return; } // O(n) void String::erase(char c) { // Create a new array. char* _array = new char[_capacity + 1]; // Copy all non-erased characters to the new array. int length = size(); for (int i = 0, j = 0; i <= length; ++i) { if (array[i] != c) _array[j++] = array[i];
  • 5. else _size--; } // Remove the old array. delete[] array; array = _array; return; } // O(n) void String::remove(int index) { // Copy all characters to the left, overwriting index. int length = this->size(); for (int i = index; i < length; ++i) array[i] = array[i + 1]; _size--; return; } // O(1) Amortized Cost due to doubling. // More info: // https://www.interviewcake.com/concept/java/dynamic-array- amortized-analysis void String::append(char c) { unsigned int length = size(); if (length >= this->capacity()) { this->reserve((length + 1) * 2); } array[length] = c; array[length + 1] = 0; _size++; return; } // O(n)
  • 6. void String::prepend(char c) { unsigned int length = size(); if (length >= this->capacity()) { this->reserve((length + 1) * 2); } for (int i = length + 1; i > 0; --i) array[i] = array[i - 1]; array[0] = c; _size++; return; } // O(n) bool String::compare(char* str) const { int length = size(); // Compare all the way up to the null. for (int i = 0; i <= length; ++i) { if (str[i] != array[i]) return false; } return true; } // O(n) bool String::compare(const String& str) const { return this->compare(str.array); } // O(n) void String::concatenate(char* str) { // Get our lengths. unsigned int strlen = 0, length = size(); while (str[strlen]) ++strlen; // Reserve the space if (length + strlen > this->_capacity) {
  • 7. this->reserve(strlen); } // Copy things over. for (unsigned int i = length, j = 0; i <= length + strlen; ++i, ++j) { this->array[i] = str[j]; } _size += strlen; return; } // O(n) void String::concatenate(String& str) { this->concatenate(str.array); return; } // O(n) inline bool exact_match(char* a, char* b) { return (!b[0]) ? true : a[0] == b[0] && exact_match(a + 1, b + 1); } // O(n^2) unsigned int String::find(char* str, int start) const { unsigned int i, length; for (i = start, length = size(); i < length; ++i) { if (exact_match(this->array + i, str)) return i; } return i; } // O(n) unsigned int String::find(char c, int start) const { unsigned int i, length;
  • 8. for (i = start, length = size(); i < length; ++i) if (array[i] == c) return i; return i; } // O(n^2) unsigned int String::find(String& str, int start) const { return this->find(str.array, start); } // O(n) void String::reverse() { int length = size() - 1; for (int i = 0; i < length / 2; ++i) { array[i] ^= array[length - i]; array[length - i] ^= array[i]; array[i] ^= array[length - i]; } return; } // O(n) void String::shift(int n) { int length = size(); for (int i = 0; i < length; ++i) { array[i] = array[i] + n % 255; if (!array[i]) ++array[i]; } return; } // O(n) int String::toInt() const { return stringtoint(this->array);
  • 9. } // O(n) since append is O(1) amortized. String String::substr(int start, int end) const { String ret; for (int i = start; i < end; ++i) ret.append(array[i]); return ret; } void String::print(std::ostream& oss) const { for (int i = 0; array[i]; ++i) oss << array[i]; } std::ostream& operator<<(std::ostream& oss, const String& str) { str.print(oss); return oss; } char String::pop_back() { if (empty()) throw "Nothing to pop"; char c = array[_size - 1]; array[_size--] = '0'; return c; }