C Exercises: Check if a string is present in the last part of another string
Check if a string ends with another string
Write a C program that accepts two strings and checks whether the second string is present in the last part of the first string.
Sample Solution:
C Code:
#include <stdio.h>
#include <string.h>
int main() {
short num1_len, num2_len;
char num1[50], num2[50];
// Prompt the user to input the first string
printf("Input the first string:\n");
scanf("%s", num1);
// Prompt the user to input the second string
printf("Input the second string:\n");
scanf("%s", num2);
// Get the lengths of the two strings
num1_len = strlen(num1);
num2_len = strlen(num2);
// Check if the second string is present in the last part of the first string
printf("Is second string present in the last part of the first string?\n");
if (num1_len == num2_len) // If the lengths are equal
if (strcmp(num1, num2) == 0) // If the strings are equal
printf("Present!\n");
else
printf("Not Present!\n");
else if (num1_len < num2_len) // If the first string is shorter than the second
printf("Not Present!\n");
else if (strstr(&num1[num1_len - num2_len - 1], num2)) // If the second string is found in the last part of the first string
printf("Present!\n");
else
printf("Not Present!\n");
return 0; // End of program
}
Sample Output:
Input the first string: abcdef Input the second string: ef Is second string present in the last part of the first string? Present!
Flowchart:
For more Practice: Solve these Related Problems:
- Write a C program to check if one string is a suffix of another using pointer comparisons.
- Write a C program to determine whether the second string occurs at the end of the first string by comparing lengths and characters.
- Write a C program to implement a function that checks for a substring at the end of a string without using library functions.
- Write a C program to compare two strings and print "Present!" if the first string ends with the second using loops.
Go to:
PREV : Find smallest value and its position in an array.
NEXT : Find heights of top three tallest buildings.
C programming Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.