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>
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>
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!