Table of Contents
Basic Palindrome Check (Case-Sensitive, Ignores Spaces/Punctuation)
Enhanced Version (Ignores Case, Spaces, and Punctuation)
Example Outputs
Key Points
Home Backend Development C++ C palindrome check example

C palindrome check example

Aug 03, 2025 am 03:01 AM

Yes, checking whether the string is palindrome can be achieved through the double-pointer method; 1. Use left and right two pointers to move from the beginning and end of the string to the center respectively; 2. In the basic version, directly compare whether the characters are equal, case sensitive and not ignore spaces and punctuations; 3. In the enhanced version, non-alphanumeric characters are skipped and converted to lowercase for comparison, so as to realize the function of ignoring case, spaces and punctuations; 4. If all corresponding characters match, the string is palindrome, otherwise it is not; the time complexity of this method is O(n) and the space complexity is O(1), which is suitable for handling various boundary situations such as empty strings, single characters and mixed-format text.

C palindrome check example

Checking if a string is a palindrome in C is a common programming task. A palindrome is a word, phrase, or sequence that reads the same forwards and backwards (ignoring case, spaces, and punctuation in some cases).

C palindrome check example

Here's a simple and clear C example that checks whether a given string is a palindrome:

Basic Palindrome Check (Case-Sensitive, Ignores Spaces/Punctuation)

 #include <iostream>
#include <string>
#include <algorithm>

bool isPalindrome(const std::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() {
    std::string input;
    std::cout << "Enter a string: ";
    std::getline(std::cin, input);

    if (isPalindrome(input)) {
        std::cout << "\"" << input << "\" is a palindrome.\n";
    } else {
        std::cout << "\"" << input << "\" is not a palindrome.\n";
    }

    return 0;
}

Enhanced Version (Ignores Case, Spaces, and Punctuation)

If you want to check palindromes more realistically (like "A man a plan a canal Panama"), use this version:

C palindrome check example
 #include <iostream>
#include <string>
#include <cctype> // for tower, isalnum

bool isPalindromeEnhanced(const std::string& str) {
    int left = 0;
    int right = str.length() - 1;

    while (left < right) {
        // Skip non-alphanumeric characters from the left
        while (left < right && !std::isalnum(str[left])) {
            left ;
        }
        // Skip non-alphanumeric characters from the right
        while (left < right && !std::isalnum(str[right])) {
            right--;
        }

        // Compare characters (case-insensitive)
        if (std::tolower(str[left]) != std::tolower(str[right])) {
            return false;
        }

        left ;
        right--;
    }
    return true;
}

int main() {
    std::string input;
    std::cout << "Enter a string: ";
    std::getline(std::cin, input);

    if (isPalindromeEnhanced(input)) {
        std::cout << "\"" << input << "\" is a palindrome.\n";
    } else {
        std::cout << "\"" << input << "\" is not a palindrome.\n";
    }

    return 0;
}

Example Outputs

  • Input: racecar → Output: is a palindrome
  • Input: hello → Output: not a palindrome
  • Input: A man a plan a canal Panama → Output: is a palindrome (with enhanced version)

Key Points

  • The two-pointer approach (left and right) is efficient: O(n) time, O(1) space.
  • Use std::isalnum() and std::tolower() to handle real-world text.
  • Always consider edge cases: empty strings, single characters, mixed case, punctuation.

Basically, just compare characters from both ends moving inward — if all match, it's a palindrome.

The above is the detailed content of C palindrome check example. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1510
276
C   Initialization techniques C Initialization techniques Jul 18, 2025 am 04:13 AM

There are many initialization methods in C, which are suitable for different scenarios. 1. Basic variable initialization includes assignment initialization (inta=5;), construction initialization (inta(5);) and list initialization (inta{5};), where list initialization is more stringent and recommended; 2. Class member initialization can be assigned through constructor body or member initialization list (MyClass(intval):x(val){}), which is more efficient and suitable for const and reference members. C 11 also supports direct initialization within the class; 3. Array and container initialization can be used in traditional mode or C 11's std::array and std::vector, support list initialization and improve security; 4. Default initialization

Object Slicing in C Object Slicing in C Jul 17, 2025 am 02:19 AM

Object slice refers to the phenomenon that only part of the base class data is copied when assigning or passing a derived class object to a base class object, resulting in the loss of new members of the derived class. 1. Object slices occur in containers that directly assign values, pass parameters by value, or store polymorphic objects in storage base classes; 2. The consequences include data loss, abnormal behavior and difficult to debug; 3. Avoiding methods include passing polymorphic objects using pointers or references, or using smart pointers to manage the object life cycle.

Using std::optional in C Using std::optional in C Jul 21, 2025 am 01:52 AM

To determine whether std::optional has a value, you can use the has_value() method or directly judge in the if statement; when returning a result that may be empty, it is recommended to use std::optional to avoid null pointers and exceptions; it should not be abused, and Boolean return values or independent bool variables are more suitable in some scenarios; the initialization methods are diverse, but you need to pay attention to using reset() to clear the value, and pay attention to the life cycle and construction behavior.

Explain RAII in C Explain RAII in C Jul 22, 2025 am 03:27 AM

RAII is an important technology used in resource management in C. Its core lies in automatically managing resources through the object life cycle. Its core idea is: resources are acquired at construction time and released at destruction, thereby avoiding leakage problems caused by manual release. For example, when there is no RAII, the file operation requires manually calling fclose. If there is an error in the middle or return in advance, you may forget to close the file; and after using RAII, such as the FileHandle class encapsulates the file operation, the destructor will be automatically called after leaving the scope to release the resource. 1.RAII is used in lock management (such as std::lock_guard), 2. Memory management (such as std::unique_ptr), 3. Database and network connection management, etc.

C   vector get first element C vector get first element Jul 25, 2025 am 12:35 AM

There are four common methods to obtain the first element of std::vector: 1. Use the front() method to ensure that the vector is not empty, has clear semantics and is recommended for daily use; 2. Use the subscript [0], and it also needs to be judged empty, with the performance comparable to front() but slightly weaker semantics; 3. Use *begin(), which is suitable for generic programming and STL algorithms; 4. Use at(0), without manually null judgment, but low performance, and throw exceptions when crossing the boundary, which is suitable for debugging or exception handling; the best practice is to call empty() first to check whether it is empty, and then use the front() method to obtain the first element to avoid undefined behavior.

C   Standard Library Explained C Standard Library Explained Jul 25, 2025 am 02:11 AM

The C standard library helps developers improve code quality by providing efficient tools. 1. STL containers should be selected according to the scene, such as vector suitable for continuous storage, list suitable for frequent insertion and deletion, and unordered_map is suitable for fast search; 2. Standard library algorithms such as sort, find, and transform can improve efficiency and reduce errors; 3. Intelligent pointers unique_ptr and shared_ptr effectively manage memory to avoid leakage; 4. Other tools such as optional, variant, and function enhance code security and expressiveness. Mastering these core functions can significantly optimize development efficiency and code quality.

What is a destructor in C  ? What is a destructor in C ? Jul 19, 2025 am 03:15 AM

The destructor in C is a special member function that is automatically called when an object is out of scope or is explicitly deleted. Its main purpose is to clean up resources that an object may acquire during its life cycle, such as memory, file handles, or network connections. The destructor is automatically called in the following cases: when a local variable leaves scope, when a delete is called on the pointer, and when an external object containing the object is destructed. When defining the destructor, you need to add ~ before the class name, and there are no parameters and return values. If undefined, the compiler generates a default destructor, but does not handle dynamic memory releases. Notes include: Each class can only have one destructor and does not support overloading; it is recommended to set the destructor of the inherited class to virtual; the destructor of the derived class will be executed first and then automatically called.

C   bit manipulation example C bit manipulation example Jul 25, 2025 am 02:33 AM

Bit operation can efficiently implement the underlying operation of integers, 1. Check whether the i-th bit is 1: Use n&(1

See all articles