您好,欢迎访问一九零五行业门户网

查找以给定后缀结尾的字符串

c++ 有一个预定义函数 substr 来返回字符串的一部分,并有一个比较函数来检查字符序列。后缀表示添加到单词末尾的一组字符。
在本文中,我们将查找以给定后缀结尾的字符串。
让我们通过一些字符串来理解后缀的示例 -
tutorialspoint - 字符n和t代表后缀。
tutorix - 字符 r、i 和 x 代表后缀。
请注意,单词中某些字符的反向长度称为后缀。
语法substr()
该函数用于通过定义字符串的输入来计算字符串中字符的长度。
compare()
该函数用于比较给定字符串或子字符串中字符的匹配情况。如果匹配的字符满足,则返回0。
算法我们将使用头文件 ‘iostream’ 和 ‘string’ 启动程序。
之后,我们将启动主函数并将字符串值声明给变量'ecom'。
稍后我们将‘ecom’数组的大小初始化为变量‘n。
现在我们通过在示例中给出不同的循环来使用相同的逻辑,并执行以下操作 -
ecom[i].substr(ecom[i].length()-total_character_in_number).compare(suffix_name)==0
在示例 1 中,我们使用 for 循环来迭代字符串 'ecom' 的每个索引。
在示例 2 中,我们使用 while 循环来迭代字符串 'ecom' 的每个索引。
在示例 1 和示例 2 中,我们使用 if 语句来表示两个方法 - substr() 和 compare() 到 ecom[i ] 它验证后缀的长度最多为某些字符,并通过将该字符进行比较方法,它将将该字符设置为等于 0,这将返回给定的后缀。
最后,我们借助字符串‘ecom[i]’打印输出语句。
示例 1在此程序中,我们将使用 for 循环执行以给定后缀结尾的字符串。
#include <iostream>#include <string>using namespace std;int main(){ string ecom[6] = {myntra,synasera,myra,condera,reseme,beautiful}; int n = sizeof(ecom)/sizeof(ecom[0]); for(int i = 0; i < n; i++) { if(ecom[i].substr(ecom[i].length() - 2).compare(ra) == 0) { cout<<the suffix ra used in the string: <<ecom[i]<<endl; } } return 0;}
输出the suffix ra used in the string: myntrathe suffix ra used in the string: synaserathe suffix ra used in the string: myrathe suffix ra used in the string: condera
示例 2在此程序中,我们将使用 while 循环执行以给定后缀结尾的字符串。
#include<iostream>#include<string>using namespace std;int main(){ string ecom[6] = {myntra,synasera,myra,colorful,reseme,beautiful}; int n = sizeof(ecom)/sizeof(ecom[0]); int i; while(i < n) { if(ecom[i].substr(ecom[i].length() - 3).compare(ful) == 0) { cout<<the suffix ful used in the string: <<ecom[i]<<endl; } i++; } return 0;}
输出the suffix ful used in the string: colorfulthe suffix ful used in the string: beautiful
结论我们探讨了以给定后缀结尾的字符串的概念。我们已经了解了“substr()”和“compare()”方法如何在多个字符串中查找相似的后缀字符。另一方面,我们也将相同的概念应用于前缀程序。该程序有助于构建应用程序,例如网络搜索框、电子表格搜索、seo 中使用的元数据等。
以上就是查找以给定后缀结尾的字符串的详细内容。
其它类似信息

推荐信息