Created
March 2, 2021 15:04
-
-
Save alexmercerind/85e51a49685590ec8fdb4b07dc264838 to your computer and use it in GitHub Desktop.
Some of fine string methods I wish were in C++
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <string> | |
#include <vector> | |
class String { | |
public: | |
static bool startsWith(std::string string, std::string subString) { | |
if (string.substr(0, subString.size()) == subString) return true; | |
else return false; | |
} | |
static std::vector<std::string> split(std::string string, std::string match) { | |
std::vector<std::string> result; | |
int matchSize = match.size(); | |
int lastIndex = 0; | |
for (int index = 0; index < string.size(); index++) { | |
if (index == string.size() - match.size() + 1) { | |
result.push_back(string.substr(lastIndex, string.size() - lastIndex)); | |
break; | |
} | |
if (string.substr(index, matchSize) == match) { | |
result.push_back(string.substr(lastIndex, index - lastIndex)); | |
lastIndex = matchSize + index; | |
} | |
} | |
return result; | |
} | |
static std::string replace(std::string string, std::string match, std::string replace) { | |
std::string result; | |
int matchSize = match.size(); | |
int lastIndex = 0; | |
int matchCounter = 0; | |
for (int index = 0; index < string.size(); index++) { | |
if (matchCounter != 0) { | |
if (matchCounter == match.size() - 1) matchCounter = 0; | |
else matchCounter++; | |
} | |
else if (index == string.size() - match.size()) { | |
result.append(replace); | |
break; | |
} | |
else if (string.substr(index, matchSize) == match && matchCounter == 0) { | |
result.append(replace); | |
lastIndex = matchSize + index; | |
matchCounter++; | |
} | |
else { | |
result.push_back(string[index]); | |
} | |
} | |
return result; | |
} | |
static std::string strip(std::string string) { | |
std::string result; | |
for (char character: string) { | |
if (character != ' ' && character != '\n') { | |
result.push_back(character); | |
} | |
} | |
return result; | |
} | |
static bool contains(std::string string, char keyword) { | |
bool result = false; | |
for (char character: string) { | |
if (character == keyword) { | |
result = true; | |
} | |
} | |
return result; | |
} | |
static std::string extract(std::string string, char start, char end) { | |
std::string result; | |
bool resultStart = false; | |
for (char character: string) { | |
if (resultStart && character == end) { | |
break; | |
} | |
else if (resultStart) { | |
result.push_back(character); | |
} | |
else if (character == start) { | |
resultStart = true; | |
} | |
} | |
return result; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment