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 检查第一个和最后一个字符是否相等的函数
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 = "nhooo"
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;
//检查第一个和最后一个字符是否相等的函数
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 = "nhooo";
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