โจทย์
ได้รับสตริง str และ conStr ทางเราต้อง ตรวจสอบว่า str เริ่มและจบด้วย conStr หรือไม่
ตัวอย่าง
Input: str = "abcProgrammingabc", conStr = "abc"
Output: True
แนวทางแก้ปัญหา
- ถ้าความยาว str < conStr -> false
- ตรวจสอบ prefix ขนาด conStr.length() เท่ากับ conStr
- ตรวจสอบ suffix ขนาด conStr.length() เท่ากับ conStr
โปรแกรมตัวอย่าง
#include <bits/stdc++.h>
using namespace std;
bool isPrefSuffPresent(string str, string conStr) {
int size = str.length(), consSize = conStr.length();
if (size < consSize) return false;
return (str.substr(0, consSize) == conStr && str.substr(size - consSize, consSize) == conStr);
}
int main() {
string str = "abcProgrammingabc", 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