
C++ 有一个预定义函数 substr 来返回字符串的一部分,并有一个比较函数来检查字符序列。后缀表示添加到单词末尾的一组字符。
在本文中,我们将查找以给定后缀结尾的字符串。
让我们通过一些字符串来理解后缀的示例 -
请注意,单词中某些字符的反向长度称为后缀。
语法
Substr()
该函数用于通过定义字符串的输入来计算字符串中字符的长度。
compare()
该函数用于比较给定字符串或子字符串中字符的匹配情况。如果匹配的字符满足,则返回0。
算法
我们将使用头文件 ‘iostream’ 和 ‘string’ 启动程序。
之后,我们将启动主函数并将字符串值声明给变量'Ecom'。
稍后我们将‘Ecom’数组的大小初始化为变量‘n。
现在我们通过在示例中给出不同的循环来使用相同的逻辑,并执行以下操作 -
Ecom[i].substr(Ecom[i].length()-total_character_in_number).compare("suffix_name")==0
示例 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: Myntra
The suffix ra used in the string: Synasera
The suffix ra used in the string: Myra
The 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: Colorful
The suffix ful used in the string: Beautiful
结论
我们探讨了以给定后缀结尾的字符串的概念。我们已经了解ߚ
.........................................................