Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fixes in stringImproved #135

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 12 additions & 15 deletions src/stringImproved.h
Original file line number Diff line number Diff line change
Expand Up @@ -59,10 +59,10 @@ class string : public std::string
}

/*
substr works the same as the [start:end] operator in python, allowing negative indexes to get the back of the string.
substr/substr_view works the same as the [start:end] operator in python, allowing negative indexes to get the back of the string.
It is also garanteed to be safe. So if you request an out of range index, you will get an empty string.
*/
string substr(const int pos = 0, const int endpos = std::numeric_limits<int>::max()) const
std::string_view substr_view(const int pos = 0, const int endpos = std::numeric_limits<int>::max()) const
{
int start = pos;
int end = endpos;
Expand All @@ -79,9 +79,14 @@ class string : public std::string
len = std::min(end, len);
if (end <= start)
{
return "";
return {};
}
return std::string::substr(start, end - start);
return std::string_view{ *this }.substr(start, end - start);
}

string substr(const int pos = 0, const int endpos = std::numeric_limits<int>::max()) const
{
return substr_view(pos, endpos);
}

string operator*(const int count)
Expand Down Expand Up @@ -146,7 +151,7 @@ class string : public std::string
}
bool endswith(char suffix) const
{
return !empty() && (*this)[length()-1] == suffix;
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is interesting, because it meant that string{}.endswith("") != string{}.endswith('\0') (the string version assumes an empty string is always present at the end of a string)

return endswith({ &suffix, 1 });
}

/*
Expand Down Expand Up @@ -187,24 +192,16 @@ class string : public std::string
{
if (sub.length() + start > length() || sub.length() < 1)
return -1;
std::string_view sv{*this};
for(unsigned int n=start; n<=length() - sub.length(); n++)
{
if(sv.substr(n, n+int(sub.length())) == sub)
if(substr_view(n, n+int(sub.length())) == sub)
return n;
}
return -1;
}
int find(char sub, int start=0) const
{
if (start >= int(length()))
return -1;
for(unsigned int n=start; n<length(); n++)
{
if((*this)[n] == sub)
return n;
}
return -1;
return find({ &sub, 1 }, start);
}

/*
Expand Down