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
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP