DEV Community

Md-Raihan-Alam
Md-Raihan-Alam

Posted on

Codewar -problem "String end with" by C

In this blog we talked about the solution that I submitted to the " 7 KYU " problem which is "String end with" by using language "C"

Let's read the question first
**_Complete the solution so that it returns true if the first argument(string) passed in ends with the 2nd argument (also a string).

Examples:

solution('abc', 'bc') // returns true
solution('abc', 'd') // returns false_**.

So simply, we need to check whether the first string ending characters are second string characters. return TRUE if they match or return FALSE if they do not match.

We will need header stdbool.h and string.h. the function will be "solution" with "bool" return data type, their parameters will be const char *string, const char *ending.

This is how the code will look like
`

include

include

bool solution(const char *string, const char *ending)
{
return true;
}
`
Now let's go further:

In the function will will take create two integer local variables and they will use strlen string function to count the length of arguments or strings. You can name the variable whatever you want as long as they do not violate Variable rules. This is how the code will look like:

int strLen=strlen(string);
int endLen=strlen(ending);

Now there is a catch, if the first string length is greater than second string length then it will dissolve the whole question so we will set it to result false there. Now the code will be:

if(endLen>strLen) return false;

Now let's go to final step, we will create a loop to go through both string to compare the characters here. we well set the condition to the end Ending string. because we do not need to go through the first string. The question asked to check whether the ending string character is present at the end of first string characters. You can use the other loop but I will go with the for loop here:


for(int i=1;i<=endLen;i++){
}

Now we will check whether the last character of first string and last character of second string is same. It will continue until the end of second string because of loop. We all know C always take or create a null character \0 at the end of string so will will minus it with loop value of int i which is equal to 1 at the very start of loop. If a single character do not match then we will return false but if it does match then the function will return true. Here is the code:

if(string[strLen-i]!=ending[endLen-i])
{
return false;
}

This is the whole code:

Image description

Top comments (0)