C++ 程序检查字符串的首尾字符是否相等


给定输入字符串,任务是检查字符串的首尾字符是否相等。

示例

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

更新日期:2019 年 10 月 18 日

993 次浏览

开启您的 职业生涯

通过完成课程获得认证

开始学习
广告
© . All rights reserved.