"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Determine if a String Ends with a Specific Substring in C++?

How to Determine if a String Ends with a Specific Substring in C++?

Published on 2024-12-11
Browse:752

How to Determine if a String Ends with a Specific Substring in C  ?

Determining String Endings in C

One common operation in string manipulation is checking if a given string concludes with another. This functionality is crucial in various applications, including text processing, pattern matching, and file analysis.

In C , there are multiple ways to ascertain if a string ends with a specific substring. One efficient method involves utilizing the std::string::compare function, available in the standard C library.

The compare function compares two strings and returns an integer value representing the result. By comparing the last portion of the original string with the potential ending substring, we can determine if they match.

The following code demonstrates how to implement this approach:

#include 

bool hasEnding(const std::string& fullString, const std::string& ending) {
    if (fullString.length() >= ending.length()) {
        return (0 == fullString.compare(fullString.length() - ending.length(), ending.length(), ending));
    } else {
        return false;
    }
}

int main() {
    std::string test1 = "binary";
    std::string test2 = "unary";
    std::string test3 = "tertiary";
    std::string test4 = "ry";
    std::string ending = "nary";

    std::cout 

In this code, we first define a function hasEnding that takes two strings as input. The function returns a boolean indicating whether the first string ends with the second.

Inside the function, we check if the length of the first string is greater than or equal to the length of the second string. If not, the function returns false.

If the length check passes, we use compare to compare the last portion of the first string with the second string. The compare function returns 0 if the two strings are equal, which is what we check to determine if the first string ends with the second.

The main function tests the hasEnding function with several input strings and outputs the results.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3