C++ program to check if first and the last characters of string are equal



Given with an input of string and the task is to check whether the first and last characters of given string is equal or not.

Example

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’

Approach used below is as follows

  • Input the string and store in an array of strings.
  • Calculate the length of a string using length() function
  • Check first and last element of a string array, if they are equal return 1 else retrun -1
  • Print the resultant output

Algorithm

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

Example

 Live Demo

#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";
}

Output

IF WE RUN THE ABOVE CODE IT WILL GENERATE FOLLOWING OUTPUT

yes it have first and last equal characters

Advertisements