在 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP