SlideShare a Scribd company logo
#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;
}

More Related Content

Similar to #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
 
2- Dimensional Arrays
2- Dimensional Arrays2- Dimensional Arrays
2- Dimensional Arrays
Education Front
 
The java language cheat sheet
The java language cheat sheetThe java language cheat sheet
The java language cheat sheet
anand_study
 
C++11 - STL Additions
C++11 - STL AdditionsC++11 - STL Additions
C++11 - STL Additions
GlobalLogic Ukraine
 
Data structure array
Data structure  arrayData structure  array
Data structure array
MajidHamidAli
 
Unit 2
Unit 2Unit 2
Unit 2
TPLatchoumi
 
Unit 3 arrays and_string
Unit 3 arrays and_stringUnit 3 arrays and_string
Unit 3 arrays and_string
kirthika jeyenth
 
DS Code (CWH).docx
DS Code (CWH).docxDS Code (CWH).docx
DS Code (CWH).docx
KamalSaini561034
 
Java cheatsheet
Java cheatsheetJava cheatsheet
Java cheatsheet
Anass SABANI
 
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
 
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
Meghaj Mallick
 
Arrays
ArraysArrays
Arrays
AnaraAlam
 
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
rohinitalekar1
 
Data Structures Using C Practical File
Data Structures Using C Practical File Data Structures Using C Practical File
Data Structures Using C Practical File
Rahul Chugh
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
piyush Kumar Sharma
 
VIT351 Software Development VI Unit2
VIT351 Software Development VI Unit2VIT351 Software Development VI Unit2
VIT351 Software Development VI Unit2
YOGESH SINGH
 
Pointers and arrays
Pointers and arraysPointers and arrays
Pointers and arrays
Bhuvana Gowtham
 
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
 

Similar to #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
 

More from 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
 
-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
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
 
-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
gertrudebellgrove
 
- 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
gertrudebellgrove
 
-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
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
 
-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
gertrudebellgrove
 
- 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
gertrudebellgrove
 
- 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
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
 
- 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
gertrudebellgrove
 
- 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
gertrudebellgrove
 
- 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
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
 
- 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
gertrudebellgrove
 
) 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
gertrudebellgrove
 
(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
gertrudebellgrove
 
( 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
gertrudebellgrove
 
++ 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
gertrudebellgrove
 

More from 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
 

Recently uploaded

How to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP ModuleHow to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP Module
Celine George
 
The basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptxThe basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptx
heathfieldcps1
 
Community pharmacy- Social and preventive pharmacy UNIT 5
Community pharmacy- Social and preventive pharmacy UNIT 5Community pharmacy- Social and preventive pharmacy UNIT 5
Community pharmacy- Social and preventive pharmacy UNIT 5
sayalidalavi006
 
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
RitikBhardwaj56
 
The Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collectionThe Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collection
Israel Genealogy Research Association
 
MARY JANE WILSON, A “BOA MÃE” .
MARY JANE WILSON, A “BOA MÃE”           .MARY JANE WILSON, A “BOA MÃE”           .
MARY JANE WILSON, A “BOA MÃE” .
Colégio Santa Teresinha
 
Pride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School DistrictPride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School District
David Douglas School District
 
BBR 2024 Summer Sessions Interview Training
BBR  2024 Summer Sessions Interview TrainingBBR  2024 Summer Sessions Interview Training
BBR 2024 Summer Sessions Interview Training
Katrina Pritchard
 
Pengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptxPengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptx
Fajar Baskoro
 
How to Make a Field Mandatory in Odoo 17
How to Make a Field Mandatory in Odoo 17How to Make a Field Mandatory in Odoo 17
How to Make a Field Mandatory in Odoo 17
Celine George
 
How to Setup Warehouse & Location in Odoo 17 Inventory
How to Setup Warehouse & Location in Odoo 17 InventoryHow to Setup Warehouse & Location in Odoo 17 Inventory
How to Setup Warehouse & Location in Odoo 17 Inventory
Celine George
 
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat  Leveraging AI for Diversity, Equity, and InclusionExecutive Directors Chat  Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
TechSoup
 
Life upper-Intermediate B2 Workbook for student
Life upper-Intermediate B2 Workbook for studentLife upper-Intermediate B2 Workbook for student
Life upper-Intermediate B2 Workbook for student
NgcHiNguyn25
 
Film vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movieFilm vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movie
Nicholas Montgomery
 
Walmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdfWalmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdf
TechSoup
 
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama UniversityNatural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Akanksha trivedi rama nursing college kanpur.
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
Nguyen Thanh Tu Collection
 
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
National Information Standards Organization (NISO)
 
S1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptxS1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptx
tarandeep35
 
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdfANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
Priyankaranawat4
 

Recently uploaded (20)

How to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP ModuleHow to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP Module
 
The basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptxThe basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptx
 
Community pharmacy- Social and preventive pharmacy UNIT 5
Community pharmacy- Social and preventive pharmacy UNIT 5Community pharmacy- Social and preventive pharmacy UNIT 5
Community pharmacy- Social and preventive pharmacy UNIT 5
 
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
 
The Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collectionThe Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collection
 
MARY JANE WILSON, A “BOA MÃE” .
MARY JANE WILSON, A “BOA MÃE”           .MARY JANE WILSON, A “BOA MÃE”           .
MARY JANE WILSON, A “BOA MÃE” .
 
Pride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School DistrictPride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School District
 
BBR 2024 Summer Sessions Interview Training
BBR  2024 Summer Sessions Interview TrainingBBR  2024 Summer Sessions Interview Training
BBR 2024 Summer Sessions Interview Training
 
Pengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptxPengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptx
 
How to Make a Field Mandatory in Odoo 17
How to Make a Field Mandatory in Odoo 17How to Make a Field Mandatory in Odoo 17
How to Make a Field Mandatory in Odoo 17
 
How to Setup Warehouse & Location in Odoo 17 Inventory
How to Setup Warehouse & Location in Odoo 17 InventoryHow to Setup Warehouse & Location in Odoo 17 Inventory
How to Setup Warehouse & Location in Odoo 17 Inventory
 
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat  Leveraging AI for Diversity, Equity, and InclusionExecutive Directors Chat  Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
 
Life upper-Intermediate B2 Workbook for student
Life upper-Intermediate B2 Workbook for studentLife upper-Intermediate B2 Workbook for student
Life upper-Intermediate B2 Workbook for student
 
Film vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movieFilm vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movie
 
Walmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdfWalmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdf
 
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama UniversityNatural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
 
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
 
S1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptxS1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptx
 
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdfANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.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; }