Cho hai chuỗi str và conStr. Nhiệm vụ: kiểm tra str có bắt đầu và kết thúc bằng conStr không.
Ví dụ:
Đầu vào: str = "abcprogrammingabc", conStr = "abc"
Đầu ra: True
Phương pháp giải
Kiểm tra độ dài str >= conStr. So sánh tiền tố và hậu tố độ dài conStr với conStr.
Chương trình minh họa
Ví dụ
#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;
}
Kết quả
The string starts and ends with another string