473,837 Members | 1,494 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Determine if a character string is palindromic

Hello experts,

I write a function named palindrome to determine if a character string
is palindromic, and test it with some example strings. Is it suitable
to add it to a company/project library as a small tool function
according to its quality? I will be very happy to get your suggestion
from every aspect on it: interface design, C language knowledge or
algorithm efficient.

Sincerely,

lovecreatesbeau ty
/* Filename : palindrome.c
* Function : bool palindrome(char *s);
* Description: to determine if a character string is palindromic
* Date : 8 May 2006
*/

#include <stdbool.h>
#include <stddef.h>
#include <string.h>

bool palindrome(char *s)
{
bool palindromic = true;
size_t len = strlen(s);

if (len > 1)
{
for (unsigned i = 0; i < len / 2; ++i)
{
if (s[i] != s[len - 1 - i])
{
palindromic = false;
break;
}
}
}

return palindromic;
}
/* test */
#include <stdio.h>

int main()
{
printf("%i\n", palindrome("dee d"));
printf("%i\n", palindrome("dee ds"));
}

/*
$ gcc -W -Wall -std=c99 -pedantic palindrome.c
$ ./a.out
1
0
$
*/

May 8 '06 #1
25 6556
lovecreatesbeau ty said:
Hello experts,

I write a function named palindrome to determine if a character string
is palindromic, and test it with some example strings. Is it suitable
to add it to a company/project library as a small tool function
according to its quality? I will be very happy to get your suggestion
from every aspect on it: interface design, C language knowledge or
algorithm efficient.

You might want to test it with these well-known palindromes:

"Madam, I'm Adam!"
"Able was I, ere I saw Elba."
"A man, a plan, a canal - Panama!"

Does it correctly identify them as palindromes?

(By the way, that question was rhetorical.)

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
May 8 '06 #2
lovecreatesbeau ty opined:
Hello experts,

I write a function named palindrome to determine if a character
string is palindromic, and test it with some example strings. Is it
suitable to add it to a company/project library as a small tool
function according to its quality? I will be very happy to get your
suggestion from every aspect on it: interface design, C language
knowledge or algorithm efficient.

Sincerely,

lovecreatesbeau ty
/* Filename : palindrome.c
* Function : bool palindrome(char *s);
* Description: to determine if a character string is palindromic
* Date : 8 May 2006
*/

#include <stdbool.h>
#include <stddef.h>
#include <string.h>

bool palindrome(char *s)
{
bool palindromic = true;
size_t len = strlen(s);

if (len > 1)
{
for (unsigned i = 0; i < len / 2; ++i)
{
if (s[i] != s[len - 1 - i])
{
palindromic = false;
break;
}
}
}

return palindromic;
}
/* test */
#include <stdio.h>

int main()
{
printf("%i\n", palindrome("dee d"));
printf("%i\n", palindrome("dee ds"));
}

/*
$ gcc -W -Wall -std=c99 -pedantic palindrome.c
$ ./a.out
1
0
$
*/


Apart from the fact that it doesn't work, it looks fairly good.
Did you consider upper/lower case? Try: "Ana voli Milovana".
Or, alternatively, you need to define "palindrome " more precisely.

--
Microsoft is not the answer.
Microsoft is the question.
NO (or Linux) is the answer.
(Taken from a .signature from someone from the UK, source unknown)

<http://clc-wiki.net/wiki/Introduction_to _comp.lang.c>

May 8 '06 #3
lovecreatesbeau ty wrote:
Hello experts,

I write a function named palindrome to determine if a character string
is palindromic, and test it with some example strings. Is it suitable
to add it to a company/project library as a small tool function
according to its quality? I will be very happy to get your suggestion
from every aspect on it: interface design, C language knowledge or
algorithm efficient.

Sincerely,

lovecreatesbeau ty
/* Filename : palindrome.c
* Function : bool palindrome(char *s);
* Description: to determine if a character string is palindromic
* Date : 8 May 2006
*/

#include <stdbool.h>
I am not a fan of stdbool.h but that's just me.
#include <stddef.h>
#include <string.h>

bool palindrome(char *s)
If the function does not modify the string pointed to by s (and it
doesn't, I looked ahead), it would be better to indicate this:

bool palindrome (const char *s)
{
bool palindromic = true;
size_t len = strlen(s);

if (len > 1)
{
for (unsigned i = 0; i < len / 2; ++i)
What happens if len/2 > UINT_MAX but less than SIZE_MAX?
I would declare i as size_t.
{
if (s[i] != s[len - 1 - i])
{
palindromic = false;
That's quite a narrow definition of palindrome you have there. A
generally well-accepted definition of palindrome from wikipedia states:

"A palindrome is a word, phrase, number or other sequence of units
(such as a strand of DNA) that has the property of reading the same in
either direction (the adjustment of punctuation and spaces between
words is generally permitted)"

Your example does not allow things like:
"Aba"
"A, A"
which most people would consider to be palindromic.
break;
}
}
}

return palindromic;
}


Below is my version of the function, the main difference is the fact
that it is much less strict than yours ignoring all non-alphanumeric
characters:

#include <stddef.h>
#include <string.h>
#include <ctype.h>

int palindrome(cons t char *s)
{
size_t len = strlen(s);
const char *left, *right;

if (len > 1) {
left = s; right = s+(len-1);
while (left < right) {
if (!isalnum(*left )) {
left++;
continue;
}
if (!isalnum(*righ t)) {
right--;
continue;
}
if (toupper(*left) == toupper(*right) ) {
left++, right--;
continue;
} else {
return 1;
}
}
}
return 0;
}

/* test */
#include <stdio.h>
#define BUF_SIZE 80

int main(void)
{
char buf[BUF_SIZE];
while (fgets(buf, 80, stdin) != NULL)
palindrome(buf) ? puts("Palindrom e") : puts("Not a palindrome");
return 0;
}

Robert Gamble

May 8 '06 #4

Robert Gamble wrote:
Below is my version of the function, the main difference is the fact
that it is much less strict than yours ignoring all non-alphanumeric
characters:

#include <stddef.h>
#include <string.h>
#include <ctype.h>

int palindrome(cons t char *s)
{
size_t len = strlen(s);
const char *left, *right;

if (len > 1) {
left = s; right = s+(len-1);
while (left < right) {
if (!isalnum(*left )) {
left++;
continue;
}
if (!isalnum(*righ t)) {
right--;
continue;
}
if (toupper(*left) == toupper(*right) ) {
left++, right--;
continue;
} else {
return 1;
That should be return 0;
}
}
}
return 0;


And that should be return 1;

Robert Gamble

May 8 '06 #5
lovecreatesbeau ty wrote:

I write a function named palindrome to determine if a character string
is palindromic, and test it with some example strings. Is it suitable
to add it to a company/project library as a small tool function
according to its quality? I will be very happy to get your suggestion
from every aspect on it: interface design, C language knowledge or
algorithm efficient.

Sincerely,

lovecreatesbeau ty

/* Filename : palindrome.c
* Function : bool palindrome(char *s);
* Description: to determine if a character string is palindromic
* Date : 8 May 2006
*/

.... snip code ...

I think you will find the following somewhat simpler. It doesn't
need the C99 stdbool.h include, and guarantees not to modify the
input string. It also handles the silly cases.

#include <stdio.h>
#include <string.h>

/* Returns 1 for palindrome, 0 for non-palindrome */
/* ispalindrome is a reserved function name */
int qpalindrome(con st char *s)
{
const char *p;

/* null and empty strings are not palindromes */
if (s && *s) {
p = s + strlen(s) - 1;
while (p > s)
if (*p-- != *s++) return 0;
return 1;
}
return 0;
} /* qpalindrome */

/* It is left as an exercise to allow mixed case. */
/* or to elide blanks */

void check(const char *s)
{
if (s) printf("\"%s\" ", s);
if (qpalindrome(s) ) puts("is");
else puts("isn't");
} /* check */

int main(void)
{
puts("Checking palindromes");
check("noon");
check("Noon");
check("dad");
check("Dad");
check(NULL);
check("");
return 0;
} /* main */

--
"If you want to post a followup via groups.google.c om, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
More details at: <http://cfaj.freeshell. org/google/>
Also see <http://www.safalra.com/special/googlegroupsrep ly/>
May 8 '06 #6
Robert Gamble wrote:
Robert Gamble wrote:
return 1;


That should be return 0;
}
}
}
return 0;


And that should be return 1;


Is there any particular reason that functions often behave this way?
If they succeed, they return 0, which in C is false, and vice versa.

Hmm, while I was writing this it occurred to me that it can have
something to do with error reporting. Different return values can
indicate different errors. Is that the reason?
May 8 '06 #7
john opined:
Robert Gamble wrote:
Robert Gamble wrote:
return 1;


That should be return 0;
}
}
}
return 0;


And that should be return 1;


Is there any particular reason that functions often behave this way?
If they succeed, they return 0, which in C is false, and vice versa.

Hmm, while I was writing this it occurred to me that it can have
something to do with error reporting. Different return values can
indicate different errors. Is that the reason?


Probably because returning 0 from `main()` is an indication of
successful program termination.

--
"Besides, I think [Slackware] sounds better than 'Microsoft,' don't
you?"
(By Patrick Volkerding)

<http://clc-wiki.net/wiki/Introduction_to _comp.lang.c>

May 8 '06 #8
"lovecreatesbea uty" <lo************ ***@gmail.com> writes:
I write a function named palindrome to determine if a character string
is palindromic, and test it with some example strings. Is it suitable
to add it to a company/project library as a small tool function
according to its quality? I will be very happy to get your suggestion
from every aspect on it: interface design, C language knowledge or
algorithm efficient.

/* Filename : palindrome.c
* Function : bool palindrome(char *s);
* Description: to determine if a character string is palindromic
* Date : 8 May 2006
*/

#include <stdbool.h>
#include <stddef.h>
#include <string.h>

bool palindrome(char *s)
{
bool palindromic = true;
size_t len = strlen(s);

if (len > 1)
{
for (unsigned i = 0; i < len / 2; ++i)
{
if (s[i] != s[len - 1 - i])
{
palindromic = false;
break;
}
}
}

return palindromic;
}
/* test */
#include <stdio.h>

int main()
{
printf("%i\n", palindrome("dee d"));
printf("%i\n", palindrome("dee ds"));
}


Your use of <stdbool.h> and of a declaration within a for loop mean
your program will work only with a C99 implementation, or with an
implementation that provides these features as an extension. Only you
can decide whether that's a problem. Converting the program to C90,
or rather to the common subset of C90 and C99, is straightforward .

You use an unsigned object to iterate through the string, but the
upper bound of the iteration is of type size_t. It's conceivable that
size_t could be bigger than unsigned, and that your loop could fail
for a very long string. You're unlikely to run into this problem
either in practice or in testing, unless you're specifically looking
for it. On many implementations , you'll never see a problem (i.e.,
testing can never reveal the bug). In other words, this bug is
particularly insidious.

The printf statements invoke undefined behavior. Your palindrome()
function returns a bool; printf's "%i" expects an int.

Note that "%i" is equivalent to "%d" in a printf format string; "%d"
is much more common in my experience. Using "%i" is perfectly correct
(if the corresponding argument is an int), but seeing it forces me to
pause and wonder why the author chose to use "%i" rather than "%d".
Perhaps the author thought there was a difference, and is failing to
express something significant. This is a minor style issue; feel free
to ignore it. (Note that "%d" and "%i" do behave differently in
scanf.)

You haven't defined the term "palindromi c". The usual definition
ignores whitespace, punctuation, and the distinction between upper and
lower case; for example, "A man, a plan, a canal, Panama!" is
considered to be a palindrome. If you want to use a simpler
definition, that's fine, but you need to state clearly what definition
you're using.

Finally, the only use I've ever seen for a function to determine
whether a string is a palindrome is as an exercise in a programming
class or other tutorial. I can't imagine including such a function,
however well implemented, in a library, or calling it other than in a
test of the function itself.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
May 8 '06 #9
On 2006-05-08, john <no@email.com > wrote:
Robert Gamble wrote:
Robert Gamble wrote:
return 1;


That should be return 0;
}
}
}
return 0;


And that should be return 1;


Is there any particular reason that functions often behave this way?
If they succeed, they return 0, which in C is false, and vice versa.

Hmm, while I was writing this it occurred to me that it can have
something to do with error reporting. Different return values can
indicate different errors. Is that the reason?


I always assumed that was the basic reason. Occasionally people write
functions that return boolean "true for success", and often functions
that return pointers return NULL for failure, so you always have to be a
bit careful with

if (f())
/* succeeded or failed? */

etc.
May 8 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
36094
by: Ren? M?hle | last post by:
I have a psp script with a procedure just to run an update on one table. The Problem occurs when I try to compile this script with pspload: ORA-20006: "frsys_updatereport.psp": compilation failed with the following errors. ORA-06502: PL/SQL: numeric or value error: character string buffer too small Here the whole script:
1
3476
by: rusttree | last post by:
I'm working on a program that manipulates bmp files. I know the offset location of each piece of relevent data within the bmp file. For example, I know the 18th through 21st byte is an integer value representing the width of the bmp image. So far, I have been able to use fstream's seek, write, and read to pull out chucks of bytes and convert them to usable integers straight out of the binary file. It works well, but over the course of...
2
13219
by: jt | last post by:
Looking for an example how to convert and CString to an ASCII character string. Any examples on how to do this? Thank you, jt
0
2184
by: MLH | last post by:
Is an apostrophe a character of special significance to MySQL in a way that would cause "Bob's dog" to become translated into a 12-character string when typed into a MySQL memo field? If I type Bob's dog into an Access memo field, I get a string that is 9-characters long. When I read "Bob's dog" from a memo field in a MySQL table attacted to MS Access via MyODBC driver, it displays as "Bob's dog" - a twelve character string. the '...
2
9299
by: Roy Rodsson via .NET 247 | last post by:
Hi all! I am using a stored procedure in SQL2000 for retrieving fileinformations from a db. the table as an uniqueidentifier for the file information. The stored procedure has a variable called fileIds that is oftype varchar. I am putting in a comma separated string with ids (such as:'9B176B0C-CA03-49C9-A2E7-063038E7CF20','9B176B0C-CA03-49C9-A2E7-063038E7CF22','9B176B0C-CA03-49C9-A2E7-063038E7CF23') However, when I execute the sp via...
7
2516
by: Justin | last post by:
i need to build the unsigned character string: "PR0N\0Spam\0G1RLS\0Other\0Items\0\0\0" from the signed character string: "PR0N Spam G1RLS Other Items" Tokeninzing the character string is not a problem. I can't solve my concatenation problem. I've researched this topic extensively and I've found nothing to help. Failure resulted when I used memcpy,_mbscat, and various other methods. If anyone knows how to build a unsigned
5
4855
by: Karthik | last post by:
Hello! I am not a wizard in this area! Just need some help out in this. I am trying to convert bstr string to new character string. Here is the snippet of my code. **** Code Start**** GlobalInterfacePtr->GetName(bstr, bstrTNamePtr, &retVal);
5
9259
by: Paul Aspinall | last post by:
Hi I want to send an ASCII character string / stream to an IP address. I basically have 6 barcode printers, and a web interface. Depending on what is entered on the web page, will determine which printer the label is printed on (ie. which IP address the ASCII string / stream is sent to). How can I send an ASCII string / stream to an IP address??
8
11893
by: Brand Bogard | last post by:
Does the C standard include a library function to convert an 8 bit character string to a 16 bit character string?
0
9843
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9682
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10575
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10628
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9406
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
7004
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5670
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5850
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
4043
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.