Palindrome String solution in c++
Here is an example of a solution to check if a string is a palindrome in C++:
#include <iostream>
#include <string>
bool isPalindrome(const std::string& str) {
int start = 0;
int end = str.length() - 1;
while (start < end) {
if (str[start] != str[end]) {
return false;
}
start++;
end--;
}
return true;
}
int main() {
std::string str;
std::cout << "Enter a string: ";
std::cin >> str;
if (isPalindrome(str)) {
std::cout << "The string is a palindrome." << std::endl;
} else {
std::cout << "The string is not a palindrome." << std::endl;
}
return 0;
}
Explanation:
Step 1: Include necessary libraries
#include <iostream>
#include <string>
This code snippet includes the necessary libraries for input/output operations and string manipulation in C++.
Step 2: Define the isPalindrome
function
bool isPalindrome(const std::string& str) {
int start = 0;
int end = str.length() - 1;
while (start < end) {
if (str[start] != str[end]) {
return false;
}
start++;
end--;
}
return true;
}
This function takes a const std::string&
parameter str
and returns a boolean value indicating whether the string is a palindrome or not. It uses two indices, start
and end
, to compare characters from both ends of the string. If at any point the characters at start
and end
indices are not equal, it returns false
. If the loop completes without finding any unequal characters, it returns true
.
Step 3: Define the main
function
int main() {
std::string str;
std::cout << "Enter a string: ";
std::cin >> str;
if (isPalindrome(str)) {
std::cout << "The string is a palindrome." << std::endl;
} else {
std::cout << "The string is not a palindrome." << std::endl;
}
return 0;
}
The main
function is the entry point of the program. It prompts the user to enter a string, reads the input using std::cin
, and assigns it to the str
variable. Then it calls the isPalindrome
function to check if the entered string is a palindrome or not. Finally, it prints the appropriate message based on the result.
Step 4: Return the result
return 0;
This statement returns 0
to indicate successful execution of the program.
Note: It's important to include the necessary libraries, define the isPalindrome
function, and call it from the main
function to check if a string is a palindrome in C++.