กำหนดด้วยอินพุตสตริงและภารกิจคือตรวจสอบว่าอักขระตัวแรกและตัวสุดท้ายของสตริงที่กำหนดเท่ากันหรือไม่
ตัวอย่าง
Input-: study Output-: not equal As the starting character is ‘s’ and the end character of a string is ‘y’ Input-: nitin Output-: yes it have first and last equal characters As the starting character is ‘n’ and the end character of a string is ‘n’
แนวทางที่ใช้ด้านล่างมีดังนี้ −
- ป้อนสตริงและเก็บไว้ในอาร์เรย์ของสตริง
- คำนวณความยาวของสตริงโดยใช้ฟังก์ชัน length()
- ตรวจสอบองค์ประกอบแรกและสุดท้ายของอาร์เรย์สตริง หากมีค่าเท่ากัน ให้คืนค่า -1 ให้รันใหม่ -1
- พิมพ์ผลลัพธ์ที่ได้
อัลกอริทึม
Start Step 1-> declare function to check if first and last charcters are equal or not int check(string str) set int len = str.length() IF (len < 2) return -1 End If (str[0] == str[len - 1]) return 1 End Else return 0 End Step 2->Int main() declare string str = "tutorialsPoint" set int temp = check(str) If (temp == -1) Print “enter valid input" End Else if (temp == 1) Print "yes it have first and last equal characters" End Else Print "Not equal” Stop
ตัวอย่าง
#include<iostream>
using namespace std;
//function to check if first and last charcters are equal or not
int check(string str) {
int len = str.length();
if (len < 2)
return -1;
if (str[0] == str[len - 1])
return 1;
else
return 0;
}
int main() {
string str = "tutorialsPoint";
int temp = check(str);
if (temp == -1)
cout<<"enter valid input";
else if (temp == 1)
cout<<"yes it have first and last equal characters";
else
cout<<"Not equal";
} ผลลัพธ์
หากเราเรียกใช้โค้ดข้างต้น จะเกิดผลลัพธ์ดังต่อไปนี้
yes it have first and last equal characters