First of all, you should pass the std::string
by const reference and not by value, therefore, replace std::string s
by const std::string& s
, otherwise you will make a whole copy of the string everytime you invoke the function.
Also, you program may crash if the std::string
is empty since you're doing std::size_t j = s.length() - 1;
. If s.length() == 0
, j
will probably be a big number and you will end up with a segfault due to an out of range index.
As suggested by Loki in the comments, you could also use a for
loop instead of a while
loop in order for your code to look cleaner.
Yet another suggestion by Jamal: using std::string::size_type
instead of std::size_t
(and removing #include <cstddef>
by the way) would be more idiomatic. The type returned by std::string::length
is not required to be std::size_t
but std::string::size_type
.
Therefore, I would rewrite it as:
bool is_palindromic(const std::string& s)
{
if (s.empty())
{
// You can return true if you think that
// an empty string is a palyndrome
return false;
}
for (std::string::size_type i=0, j=s.length()-1
; i < j ; ++i, --j)
{
if (s[i] != s[j]) {
return false;
}
}
return true;
}