1
- // Write a c program to reverse a string using user-defined function.
1
+ // Write a function to check whether a given string is palindrome or not
2
2
3
3
// Header Files
4
4
#include <stdio.h>
10
10
// Function Declarations
11
11
int strLength (char []);
12
12
char * strReverse (char []);
13
+ char * copyString (char [], char []);
14
+ int compareStrings (char [], char []);
13
15
int isStrPalindrome (char []);
14
16
15
17
// Main Function Start
16
18
int main ()
17
19
{
18
20
char str [ARRAY_SIZE ];
19
21
20
- printf ("\nEnter Any String (MAX CHARACTERS %d) => " , ARRAY_SIZE - 1 );
22
+ printf ("\nEnter Any String to Check Whether It is Palindrome or Not (MAX CHARACTERS %d) => " , ARRAY_SIZE - 1 );
21
23
fgets (str , ARRAY_SIZE , stdin ); // Input String
22
24
str [strcspn (str , "\n" )] = '\0' ; // Replace '\n' character with '\0' in str
23
25
24
- printf ("\nString Before Reversing => %s" , str );
25
-
26
- printf ("\nString After Reversing => %s" , strReverse (str ));
26
+ if (isStrPalindrome (str ))
27
+ printf ("\nYes, \"%s\" is Palindrome..." , str );
28
+ else
29
+ printf ("\nNo, \"%s\" is not Palindrome..." , str );
27
30
28
31
putch ('\n' );
29
32
getch ();
@@ -47,14 +50,10 @@ int strLength(char str[])
47
50
// Function to Reverse a String
48
51
char * strReverse (char str [])
49
52
{
50
- int length = 0 ;
53
+ int length = strLength ( str ) ;
51
54
char temp ;
52
55
53
- // Find Length of str
54
- while (str [length ])
55
- length ++ ;
56
-
57
- // // Reverse copyStr
56
+ // Reverse str
58
57
int beg = 0 , end = length - 1 ;
59
58
while (beg < end )
60
59
{
@@ -69,11 +68,42 @@ char *strReverse(char str[])
69
68
return str ;
70
69
}
71
70
71
+ // Function to Copy One String into Another
72
+ char * copyString (char des [], char src [])
73
+ {
74
+ // Copy str into copy
75
+ int i = 0 ;
76
+ for (i = 0 ; src [i ]; i ++ )
77
+ des [i ] = src [i ];
78
+
79
+ des [i ] = '\0' ;
80
+
81
+ return des ;
82
+ }
83
+
84
+ // Function to Check Whether a Given String an Alphanumeric String or Not
85
+ int compareStrings (char str1 [], char str2 [])
86
+ {
87
+ for (int i = 0 ; str1 [i ] || str2 [i ]; i ++ )
88
+ {
89
+ if (str1 [i ] > str2 [i ])
90
+ return str1 [i ] - str2 [i ];
91
+ else if (str1 [i ] < str2 [i ])
92
+ return str1 [i ] - str2 [i ];
93
+ }
94
+
95
+ return 0 ;
96
+ }
97
+
72
98
// Function to Check Whether a Given String is Palindrome or Not
73
99
int isStrPalindrome (char str [])
74
100
{
101
+ char copyStr [strLength (str ) + 1 ]; // create a string to copy str
102
+ copyString (copyStr , str ); // copy str into copyStr
103
+ strReverse (copyStr ); // reverse copyStr
75
104
76
- if (copyStr )
105
+ if (compareStrings (copyStr , str ))
106
+ return 0 ; // String is not Palindrome
77
107
78
- return str ;
108
+ return 1 ; // String is Palindrome
79
109
}
0 commit comments