ในปัญหานี้ เราได้รับสองสตริง str และ corStr งานของเราคือ ค้นหาว่าสตริงเริ่มต้นและสิ้นสุดด้วยสตริงอื่นที่กำหนดหรือไม่
มาดูตัวอย่างเพื่อทำความเข้าใจปัญหากัน
ป้อนข้อมูล: str =“abcprogrammingabc” conStr =“abc”
ผลลัพธ์: จริง
แนวทางแก้ไข:
ในการแก้ปัญหา เราต้องตรวจสอบว่าสตริงเริ่มต้นและลงท้ายด้วย conStr หรือไม่ สำหรับสิ่งนี้ เราจะหาความยาวของ string และ corStr จากนั้นเราจะตรวจสอบว่า len(String)> len(conStr) ถ้าไม่คืนค่าเท็จ
ตรวจสอบว่าคำนำหน้าและส่วนต่อท้ายของขนาด 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