首頁  >  文章  >  後端開發  >  尋找以給定後綴結尾的字串

尋找以給定後綴結尾的字串

PHPz
PHPz轉載
2023-08-30 15:41:04498瀏覽

尋找以給定後綴結尾的字串

C 有一個預先定義函數 substr 來傳回字串的一部分,並且有一個比較函數來檢查字元序列。後綴表示添加到單字末尾的一組字元。

在本文中,我們將尋找以給定後綴結尾的字串。

讓我們透過一些字串來理解後綴的範例 -

  • Tutorialspoint - 字元nt代表字尾。

  • Tutorix - 字元 r、ix 代表後綴。

請注意,單字中某些字元的反向長度稱為後綴。

文法

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 中使用的元資料等。

以上是尋找以給定後綴結尾的字串的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除