Home > Backend Development > C++ > body text

How to Determine if a String Has a Specific Suffix in C ?

DDD
Release: 2024-11-01 01:35:02
Original
641 people have browsed it

How to Determine if a String Has a Specific Suffix in C  ?

Determining String Suffixes in C

In C , determining whether a string possesses a specific suffix requires an efficient and reliable approach. To address this need, the article explores an effective means of ascertaining this information.

Identifying String Endings

To establish if a string concludes with a particular substring, C offers the string::compare() function. This method enables the comparison of a specified range of characters within a string to another provided string.

Implementation

The following code snippet demonstrates the usage of string::compare() for suffix identification:

<code class="cpp">#include <iostream>

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

This function accepts two string parameters, the full string to be checked and the potential ending. It calculates if the full string's length meets or exceeds the ending's length and then compares the relevant portions of the full string with the ending using string::compare().

Example Usage

The provided example demonstrates the application of the hasEnding() function:

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

    std::cout << hasEnding(test1, ending) << std::endl;
    std::cout << hasEnding(test2, ending) << std::endl;
    std::cout << hasEnding(test3, ending) << std::endl;
    std::cout << hasEnding(test4, ending) << std::endl;

    return 0;
}</code>
Copy after login

The output of this code displays the results of the suffix comparisons for the provided test strings.

The above is the detailed content of How to Determine if a String Has a Specific Suffix in C ?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!