This if statement
if(text[i] == '
')
{
text[i] = i - 1;
}
does not make a sense. Moreover as the new line character '
'
is a single character in an entered string then keeping it within the string will result that the string is not a palindrome.
You need to substitute it for the zero character ''
.
And the array reverse
does not contain a string after this loop
for (i = i, j = 0 ;i >= 0 ; --i, ++j)
{
reverse[j] = text[i];
}
Also using the function strlen
is redundant and inefficient.
The program can look the following way.
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int main(void)
{
char text[256], reverse[256];
printf( "Type a text: " );
fgets( text, sizeof( text ), stdin );
size_t n = 0;
while ( text[n] != '' )
{
if ( text[n] == '
' )
{
text[n] = '';
}
else
{
text[n] = tolower( ( unsigned char )text[n] );
++n;
}
}
reverse[n] = '';
for ( size_t i = 0; n-- != 0; i++ )
{
reverse[n] = text[i];
}
printf( "Text: "%s"
", text );
printf( "Reverse: "%s"
", reverse);
if ( strcmp( text, reverse ) == 0 )
{
printf( "The entered text "%s" is a palindrome!
", text );
}
else
{
printf( "The entered text "%s" is NOT a palindrome!
", text );
}
return 0;
}
The program output might look like
Type a text: ABC cba
Text: "abc cba"
Reverse: "abc cba"
The entered text "abc cba" is a palindrome!
In general the used by you approach when you need an auxiliary array and when the source string is being changed is not good.
Your could write a simple function as it is shown in this demonstrative program.
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int is_palindrome( const char *s )
{
size_t n = strlen( s );
size_t i = 0;
while ( i < n / 2 && tolower( ( unsigned char )s[i] ) ==
tolower( ( unsigned char )s[n -i -1] ) )
{
++i;
}
return i == n / 2;
}
int main(void)
{
char text[256];
printf( "Type a text: " );
fgets( text, sizeof( text ), stdin );
text[ strcspn( text, "
" ) ] = '';
printf( "Text: "%s"
", text );
if ( is_palindrome( text ) )
{
printf( "The entered text "%s" is a palindrome!
", text );
}
else
{
printf( "The entered text "%s" is NOT a palindrome!
", text );
}
return 0;
}
The program output might look like
Type a text: ABC cba
Text: "ABC cba"
The entered text "ABC cba" is a palindrome!
As you see the original string was not changed except the new line character '
'
was substituted for the zero character ''
.