Skip to content

Instantly share code, notes, and snippets.

@m-doughty
Created December 24, 2025 20:38
Show Gist options
  • Select an option

  • Save m-doughty/6f693260281d5157715d1b7be2955348 to your computer and use it in GitHub Desktop.

Select an option

Save m-doughty/6f693260281d5157715d1b7be2955348 to your computer and use it in GitHub Desktop.
#include <algorithm>
#include <print>
#include <span>
#include <string_view>
// Separate this out into a function to make it easier to test.
bool is_palindrome(std::string_view s) {
// Avoids manual pointer manipulation, still does n/2 checks.
// Note: integer division floors, but this is correct since given an
// odd-length string, middle char will always equal itself.
return std::equal(s.begin(), s.begin() + s.size() / 2, s.rbegin());
}
int main(int argc, char *argv[]) {
// std::span wraps a raw array (pointer + length) into something we can
// iterate safely. Note: .subspan(1) skips argv[0] (the program name).
auto args = std::span(argv, argc).subspan(1);
// Bail out early if no args provided.
if (args.empty()) {
// Use modern std::println instead of std::cout
std::println("Usage: ./palindrome arg1 [arg2 [arg3 ...]]");
// EXIT_FAILURE expands to a platform appropriate failure return
// code (usually 1).
return EXIT_FAILURE;
}
// Iterate over args, each char* implicitly converts to a string_view
// called arg (no copy, just a view). Print out whether each argument is
// a palindrome.
for (std::string_view arg : args) {
if (is_palindrome(arg)) {
std::println("'{}' is a palindrome", arg);
} else {
std::println("'{}' is not a palindrome", arg);
}
}
// EXIT_SUCCESS expands to a platform appropriate success return code
// (usually 0).
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment