Reputation: 33
So for my assignment, I have to complete the function endsWith which returns true if s1 ends with s2 (both cstrings)
Example: "sailboat", "boat" -> true Example: "mississipii", "pie" -> false
I already successfully did the program startsWith, which returns true if s1 starts with s2
bool startsWith(const char* s1, const char* s2)
{
// enter code under here
while (*s1)
{
auto *p1 = s1, *p2 = s2;
while (*p1 && *p2 && *p1 == *p2)
{
p1++;
p2++;
}
if (*p2 == '\0') {return true;}
else {return false;}
}
// enter code above this line
}
and this is the program my professor said use to find the last occurrence of a character:
int find(const char a[], char target)
{
int result = -1;
for (int i = 0; a[i] != '\0'; ++i)
if (a[i] == target)
result = i;
return result;
}
but I'm struggling finding a way of connecting the two to make endsWith. All of my attempts end with errors. And I will be the vary first to admit I have little idea what pointers really are or how to use them or what their purpose is at all, and it is by pure luck the first one passed.
This is my latest failed attempt without pointers, and it passed 5 out of 9 tests:
#include <cstring>
using namespace std;
bool endsWith(const char* s1, const char* s2)
{
int len1 = strlen(s1);
int len2 = strlen(s2);
// enter code under here
if (len2 > len1) {return false;}
for (size_t i = 0; i < len1; ++i)
{
if(s1[len1 - i - 1] != s2[len2 - i - 1]) {return false;}
}
return true;
// enter code above here
}
Edit: This is the code that works:
if (len2 > len1) {return false;}
size_t offset = len1 - len2;
s1 += offset;
return (strcmp(s1, s2) == 0);
Upvotes: 1
Views: 280
Reputation: 96326
I understand that you want to write it yourself for practice.
But if you need to do it in real-world code, here's a one-liner: (requires C++20)
std::string_view(s1).ends_with(s2)
Upvotes: 0
Reputation: 104559
You tagged your question as C++, but your code technically suggests "C", which is fine with me.
A "C" solution
// returns true if "s2" ends with "s1"
// examples s1="World" and s2="Hello World" => returns true
// examples s1="Hello" and s2="Hello World" => returns false
bool endsWith(const char* s1, const char* s2)
{
size_t len1 = strlen(s1);
size_t len2 = strlen(s2);
// if s1 is longer than s2, then we can trivially reject it
if (len1 > len2)
{
return false;
}
size_t offset = len2 - len1;
s2 += offset;
return (strcmp(s1, s2) == 0);
}
Upvotes: 2
Reputation: 782
Here is how I solved it in my C++ project:
bool ends_with(string first, string second) {
if (second.size() > first.size())
return false;
return first.substr(first.size() - second.size()) == second;
}
Upvotes: 0