查詢以給定字尾結尾的字串
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: 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
結論
我們探討了以給定字尾結尾的字串的概念。我們已經瞭解了'substr()'和'compare()'方法如何查詢多個字串中相似的字尾字元。另一方面,我們還將相同的概念應用於字首程式。此程式有助於構建諸如網路上的搜尋框、電子表格搜尋、用於SEO的元資料等應用程式。
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP