check if a string is palindrome cpp
#include <iostream>
#include <string>
using namespace std;
bool isPalindrome(const string& str) {
int left = 0;
int right = str.length() - 1;
while (left < right) {
if (str[left] != str[right]) {
return false;
}
left++;
right--;
}
return true;
}
int main() {
string input;
cout << "Enter a string: ";
cin >> input;
if (isPalindrome(input)) {
cout << input << " is a palindrome." << endl;
} else {
cout << input << " is not a palindrome." << endl;
}
return 0;
}
Explanation:
#include <iostream>
and#include <string>
: These lines include necessary libraries for input-output operations and string manipulation.using namespace std;
: This line allows usage of elements in thestd
namespace without explicitly specifying it.bool isPalindrome(const string& str)
: This function takes a constant reference to a string and checks if it's a palindrome. It returns a boolean value (true
if the string is a palindrome,false
otherwise).int left = 0;
andint right = str.length() - 1;
: These variablesleft
andright
are initialized to the beginning and end of the string, respectively.while (left < right) { ... }
: Thiswhile
loop iterates until theleft
pointer crosses theright
pointer.if (str[left] != str[right]) { return false; }
: If characters atleft
andright
positions are not equal, the function immediately returnsfalse
, indicating the string is not a palindrome.left++; right--;
: Theleft
pointer is incremented, and theright
pointer is decremented in each iteration to compare the next set of characters.return true;
: If the loop completes without finding any mismatch, the function returnstrue
, indicating the string is a palindrome.int main() { ... }
: This is the main function where the user inputs a string.cout << "Enter a string: "; cin >> input;
: Asks the user to input a string, which is stored in the variableinput
.if (isPalindrome(input)) { ... } else { ... }
: Calls theisPalindrome
function with the input string and prints whether it is a palindrome or not based on the returned boolean value.