在 C++ 中找到一個字串是否以另一個給定字串開頭和結尾


在該問題中,我們得到了兩個字串 str 和 corStr。我們的任務是找到一個字串是否以另一個給定字串開頭和結尾。 

我們舉個例子來理解該問題,

輸入: str = “abcprogrammingabc” conStr = “abc”

輸出: 

解決方法: 

要解決該問題,我們需要檢查字串是否以 corStr 開頭和結尾。為此,我們將找到字串和 corStr 的長度。然後,我們將檢查 len(字串) > len(corStr),如果否,則返回假。
檢查大小為 corStr 的字首和字尾是否相等,並檢查它們是否包含 corStr。

為了說明我們解決方案的工作原理,這裡提供一個程式,

示例

動態演示

#include <bits/stdc++.h>
using namespace std;

bool isPrefSuffPresent(string str, string conStr) {
   
   int size = str.length();
   int consSize = conStr.length();
   if (size < consSize)
   return false;
   return (str.substr(0, consSize).compare(conStr) == 0 && str.substr(size-consSize, consSize).compare(conStr) == 0);
}

int main() {
   
   string str = "abcProgrammingabc";
   string conStr = "abc";
   if (isPrefSuffPresent(str, conStr))
      cout<<"The string starts and ends with another string";
   else
      cout<<"The string does not starts and ends with another string";
   return 0;
}

輸出 −

The string starts and ends with another string

更新於: 22-Jan-2021

496 次檢視

開啟你的 職業Careers

透過完成課程獲得認證

入門
廣告
© . All rights reserved.