Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

โปรแกรม C++ ตรวจสอบว่าตัวอักษรแรกและตัวสุดท้ายของสตริงเท่ากันหรือไม่


บทนำ

รับสตริงเข้ามา ต้องการตรวจสอบว่าตัวอักษรตัวแรกและตัวสุดท้ายเท่ากันหรือไม่

ตัวอย่าง

  • Input: "study" → Output: not equal (s ≠ y)
  • Input: "nitin" → Output: equal (n = n)

แนวคิด

  1. รับสตริงและหาความยาว
  2. เปรียบเทียบ str[0] กับ str[len-1]
  3. คืนค่า 1 ถ้าเท่ากัน, 0 ถ้าไม่เท่ากัน, -1 ถ้าความยาว < 2

ตัวอย่างโค้ด C++

#include <iostream>
using namespace std;

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";
    return 0;
}

ผลลัพธ์

yes it have first and last equal characters