Two string programs come up again and again in school practicals and exams: checking whether a string is a palindrome, and converting the case of its characters. Both are small programs, but together they teach you how to walk through a string, compare characters, and use ASCII codes. In this guide you will learn how to write both programs in Python, C and Java, with the logic, dry runs, tested output and an interactive tool that shows every step graphically.
Type a string and watch how a program checks it or flips the case of every letter.
Graphical view
Code
Output
What You Will Learn
- The problem statement
- How a program sees a string
- Program 1: Palindrome string
- Program 2: Convert the case of characters
- Shorter ways using built-in functions
- Common mistakes, practice questions and FAQ
Problem Statement
Input a string and determine whether it is a palindrome or not. Convert the case of the characters in a string.
The user types a string. In the first program the answer is a message saying whether the string is a palindrome. In the second program every small letter becomes a capital letter and every capital letter becomes a small letter, so “Hello World” becomes “hELLO wORLD”. The interactive tool above accepts up to 20 letters, digits or spaces.
How a Program Sees a String
A string is a row of characters. Each character has a position called an index, and the index of the first character is 0. In “Madam” the characters sit at these positions:
| Index | 0 | 1 | 2 | 3 | 4 |
|---|---|---|---|---|---|
| Character | M | a | d | a | m |
| Python negative index | -5 | -4 | -3 | -2 | -1 |
The last character is always at index len(s) - 1. Every character is also stored as a number, its ASCII code. Capital letters and small letters have different codes, and the gap between a capital letter and its small partner is always 32:
| Capital | ASCII | Small | ASCII | Difference |
|---|---|---|---|---|
| A | 65 | a | 97 | 32 |
| B | 66 | b | 98 | 32 |
| M | 77 | m | 109 | 32 |
| Z | 90 | z | 122 | 32 |
Capital letters A to Z are 65 to 90, and small letters a to z are 97 to 122. That single fact is the secret of the case conversion program.
Program 1: Palindrome String
A string is a palindrome if it reads the same forwards and backwards. Examples are “madam”, “level”, “racecar” and “noon”. The word “hello” is not, because its reverse is “olleh”.
Instead of building a reversed copy, the program uses the two-pointer method. One pointer, left, starts at the first character, and another, right, starts at the last. If the two characters are equal, both pointers move one step towards the middle. If they ever differ, the string is not a palindrome and the loop can stop at once.
Logic:
- Read the string s and make a lower case copy t, so that “Madam” and “madam” are treated alike.
- Set
left = 0,right = len(t) - 1and assumeis_pal = True. - While
left < right: ift[left] != t[right], setis_pal = Falseandbreak. Otherwise moveleftright by one andrightleft by one. - When the loop ends, print the answer according to is_pal.
The loop stops when the pointers meet or cross. For a string with an odd number of characters, the middle character is never compared, because it is its own partner.
Python program
s = input("Enter a string: ")
t = s.lower()
left = 0
right = len(t) - 1
is_pal = True
while left < right:
if t[left] != t[right]:
is_pal = False
break
left = left + 1
right = right - 1
if is_pal:
print(s, "is a palindrome")
else:
print(s, "is not a palindrome")
C program
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main() {
char s[100], t[100];
printf("Enter a string: ");
fgets(s, sizeof(s), stdin);
s[strcspn(s, "\n")] = '\0';
int n = strlen(s);
for (int i = 0; i < n; i++) {
t[i] = tolower(s[i]);
}
t[n] = '\0';
int left = 0, right = n - 1, isPal = 1;
while (left < right) {
if (t[left] != t[right]) {
isPal = 0;
break;
}
left++;
right--;
}
if (isPal) {
printf("%s is a palindrome\n", s);
} else {
printf("%s is not a palindrome\n", s);
}
return 0;
}
Java program
import java.util.Scanner;
public class StringProgram {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a string: ");
String s = sc.nextLine();
String t = s.toLowerCase();
int left = 0, right = t.length() - 1;
boolean isPal = true;
while (left < right) {
if (t.charAt(left) != t.charAt(right)) {
isPal = false;
break;
}
left++;
right--;
}
if (isPal) {
System.out.println(s + " is a palindrome");
} else {
System.out.println(s + " is not a palindrome");
}
}
}
Sample output:
Enter a string: Madam Madam is a palindrome
Another run:
Enter a string: Hello Hello is not a palindrome
Dry run for “Madam”:
| left | right | Left character | Right character | Result |
|---|---|---|---|---|
| 0 | 4 | t[0] = ‘m’ | t[4] = ‘m’ | same, move on |
| 1 | 3 | t[1] = ‘a’ | t[3] = ‘a’ | same, move on |
The loop ends and every pair matched, so it is a palindrome.
Dry run for “Hello”:
| left | right | Left character | Right character | Result |
|---|---|---|---|---|
| 0 | 4 | t[0] = ‘h’ | t[4] = ‘o’ | different, stop |
The loop ends and a pair is different, so it is not a palindrome.
Dry run for “Noon”:
| left | right | Left character | Right character | Result |
|---|---|---|---|---|
| 0 | 3 | t[0] = ‘n’ | t[3] = ‘n’ | same, move on |
| 1 | 2 | t[1] = ‘o’ | t[2] = ‘o’ | same, move on |
The loop ends and every pair matched, so it is a palindrome.
Notes on this program:
- Only the first half of the string is really compared, so a string of length n needs at most n ÷ 2 comparisons.
- The string “a” and the empty string are palindromes, because the loop does not even start.
- In C the lower case copy is made character by character with
tolower(). In JavatoLowerCase()does the same job in one call. - This version compares every character, including spaces. So “nurses run” is not a palindrome here, although “nursesrun” is. Method 3 below shows how to ignore spaces and punctuation.
Program 2: Convert the Case of Characters
To convert the case, the program looks at each character in turn and decides what kind of character it is:
- If it is a small letter (from a to z), subtract 32 from its ASCII code to get the capital letter.
- If it is a capital letter (from A to Z), add 32 to get the small letter.
- Anything else, such as a space, a digit or a symbol, is copied without any change.
Logic:
- Read the string s and start with an empty string
result. - For every character ch in s, test the three cases above and add the converted character to result.
- After the loop, print result.
In Python we use ord(ch) to get the code and chr(code) to turn a code back into a character. In C a char already is a number, so s[i] - 32 works directly. In Java we cast with (char) after the arithmetic.
Python program
s = input("Enter a string: ")
result = ""
for ch in s:
if ch >= "a" and ch <= "z":
result = result + chr(ord(ch) - 32)
elif ch >= "A" and ch <= "Z":
result = result + chr(ord(ch) + 32)
else:
result = result + ch
print("Converted string:", result)
C program
#include <stdio.h>
#include <string.h>
int main() {
char s[100];
printf("Enter a string: ");
fgets(s, sizeof(s), stdin);
s[strcspn(s, "\n")] = '\0';
for (int i = 0; s[i] != '\0'; i++) {
if (s[i] >= 'a' && s[i] <= 'z') {
s[i] = s[i] - 32;
} else if (s[i] >= 'A' && s[i] <= 'Z') {
s[i] = s[i] + 32;
}
}
printf("Converted string: %s\n", s);
return 0;
}
Java program
import java.util.Scanner;
public class StringProgram {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a string: ");
String s = sc.nextLine();
String result = "";
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (ch >= 'a' && ch <= 'z') {
result = result + (char) (ch - 32);
} else if (ch >= 'A' && ch <= 'Z') {
result = result + (char) (ch + 32);
} else {
result = result + ch;
}
}
System.out.println("Converted string: " + result);
}
}
Sample output:
Enter a string: Hello World Converted string: hELLO wORLD
Another run:
Enter a string: Class 10 AI Converted string: cLASS 10 ai
Dry run for “Hello 9A”:
| ch | ASCII code | Rule applied | Added to result |
|---|---|---|---|
| H | 72 | capital letter: 72 + 32 = 104 | h |
| e | 101 | small letter: 101 − 32 = 69 | E |
| l | 108 | small letter: 108 − 32 = 76 | L |
| l | 108 | small letter: 108 − 32 = 76 | L |
| o | 111 | small letter: 111 − 32 = 79 | O |
| (space) | 32 | not a letter: unchanged | (space) |
| 9 | 57 | not a letter: unchanged | 9 |
| A | 65 | capital letter: 65 + 32 = 97 | a |
The final result is “hELLO 9a”.
Because the program changes only letters, digits and spaces survive the conversion. The C program changes the characters inside the array s itself. The Python and Java programs build a new string, because strings in those languages cannot be changed in place.
Shorter Ways Using Built-In Functions
Method 3: Palindrome using a reversed copy
Python can reverse a string with the slice [::-1]. Then the whole check is one comparison.
s = input("Enter a string: ")
t = s.lower()
if t == t[::-1]:
print(s, "is a palindrome")
else:
print(s, "is not a palindrome")
Sample output:
Enter a string: racecar racecar is a palindrome
Java has no slice, but StringBuilder has a reverse() method, and equalsIgnoreCase() compares two strings without looking at the case.
Java program using StringBuilder
import java.util.Scanner;
public class StringProgram {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a string: ");
String s = sc.nextLine();
String rev = new StringBuilder(s).reverse().toString();
if (s.equalsIgnoreCase(rev)) {
System.out.println(s + " is a palindrome");
} else {
System.out.println(s + " is not a palindrome");
}
}
}
Method 4: Ignoring spaces and punctuation
Famous sentence palindromes, such as “A man, a plan, a canal: Panama”, ignore spaces and punctuation. First keep only the letters and digits with isalnum(), in lower case, and then compare the result with its reverse.
s = input("Enter a string: ")
t = ""
for ch in s:
if ch.isalnum():
t = t + ch.lower()
if t == t[::-1]:
print(s, "is a palindrome")
else:
print(s, "is not a palindrome")
Sample output:
Enter a string: A man, a plan, a canal: Panama A man, a plan, a canal: Panama is a palindrome
Method 5: Palindrome using recursion
A string is a palindrome if its first and last characters match and the part in between is also a palindrome. The base case is a string of 0 or 1 characters, which is always a palindrome.
def is_pal(t):
if len(t) <= 1:
return True
if t[0] != t[-1]:
return False
return is_pal(t[1:-1])
s = input("Enter a string: ")
if is_pal(s.lower()):
print(s, "is a palindrome")
else:
print(s, "is not a palindrome")
Sample output:
Enter a string: Noon Noon is a palindrome
Method 6: Case conversion with built-in functions
Python has ready-made methods for every kind of case change. Use them to check your own program, and write the loop version in exams.
| Method | What it does | Example result for “Hello World” |
|---|---|---|
| s.swapcase() | Flips every letter | hELLO wORLD |
| s.upper() | Makes all letters capital | HELLO WORLD |
| s.lower() | Makes all letters small | hello world |
| s.title() | Capital letter at the start of each word | Hello World |
s = input("Enter a string: ")
print("swapcase :", s.swapcase())
print("upper :", s.upper())
print("lower :", s.lower())
print("title :", s.title())
Sample output:
Enter a string: Hello World swapcase : hELLO wORLD upper : HELLO WORLD lower : hello world title : Hello World
Method 7: Using the character functions of C and Java
C has islower(), isupper(), toupper() and tolower() in ctype.h. Java has Character.isLowerCase(), Character.isUpperCase() and similar methods. They avoid the number 32, and they are easier to read.
C program using ctype.h
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main() {
char s[100];
printf("Enter a string: ");
fgets(s, sizeof(s), stdin);
s[strcspn(s, "\n")] = '\0';
for (int i = 0; s[i] != '\0'; i++) {
if (islower(s[i])) {
s[i] = toupper(s[i]);
} else if (isupper(s[i])) {
s[i] = tolower(s[i]);
}
}
printf("Converted string: %s\n", s);
return 0;
}
Java program using Character methods
import java.util.Scanner;
public class StringProgram {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a string: ");
String s = sc.nextLine();
String result = "";
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (Character.isLowerCase(ch)) {
result = result + Character.toUpperCase(ch);
} else if (Character.isUpperCase(ch)) {
result = result + Character.toLowerCase(ch);
} else {
result = result + ch;
}
}
System.out.println("Converted string: " + result);
}
}
Variation: only convert to upper case
If the question asks only for upper case, remove the capital-letter branch and keep the small-letter branch.
s = input("Enter a string: ")
result = ""
for ch in s:
if ch >= "a" and ch <= "z":
result = result + chr(ord(ch) - 32)
else:
result = result + ch
print("Upper case:", result)
Sample output:
Enter a string: Hello World Upper case: HELLO WORLD
Variation: count capital and small letters
s = input("Enter a string: ")
upper = 0
lower = 0
for ch in s:
if ch.isupper():
upper = upper + 1
elif ch.islower():
lower = lower + 1
print("Capital letters:", upper)
print("Small letters:", lower)
Sample output:
Enter a string: Hello World Capital letters: 2 Small letters: 8
Common Mistakes
- Forgetting the case in the palindrome check. Without
lower(), the string “Madam” is called not a palindrome, because “M” and “m” have different ASCII codes. - Starting right at len(t) instead of len(t) – 1. The last index is one less than the length. Using the length itself causes an index error.
- Forgetting to move the pointers. If left and right never change, the while loop runs forever.
- Printing the answer inside the loop. A palindrome can only be confirmed after all pairs are checked. Decide after the loop.
- Converting digits and spaces by mistake. Adding 32 to every character turns a space into a different symbol. Always test the range of the letters first.
- Trying to change a Python or Java string in place. Strings in these languages cannot be changed. Build a new string, as the programs above do.
- Not removing the newline in C.
fgets()keeps the newline character at the end, which breaks the palindrome check and prints an extra blank line. The line withstrcspn()removes it.
Practice Questions
- Check whether a sentence is a palindrome while ignoring spaces.
- Convert a string to capital letters without using upper().
- Count the vowels in a string.
- Print the words of a sentence in reverse order.
- Convert a sentence to title case without using title().
- Check whether two strings are anagrams (the same letters in a different order).
Frequently Asked Questions
What is a palindrome string?
A palindrome string reads the same forwards and backwards. Examples are madam, level, racecar and noon.
How do you check a palindrome string in Python?
Compare the string with its reverse using s == s[::-1]. For a case-insensitive check, convert the string to lower case first.
Why do we use two pointers for the palindrome program?
The two pointers compare the characters at both ends and move inwards. The program can stop at the first mismatch, and it needs no extra memory for a reversed copy.
Is a single character a palindrome?
Yes. A string with one character, and the empty string, read the same in both directions.
How do you convert uppercase to lowercase without using a built-in function?
Add 32 to the ASCII code of a capital letter. For example, “A” is 65, and 65 + 32 = 97, which is “a”.
How do you convert lowercase to uppercase without using a built-in function?
Subtract 32 from the ASCII code of a small letter. For example, “a” is 97, and 97 − 32 = 65, which is “A”.
What is the difference between swapcase(), upper() and title() in Python?
swapcase() flips the case of every letter, upper() makes every letter capital, and title() makes the first letter of each word capital and the rest small.
Why does the difference between capital and small letters equal 32?
In the ASCII table the small letters come 32 places after the capital letters, so every capital letter and its small partner differ by exactly 32.
Can I use these programs for a sentence with punctuation?
The case conversion program works with any text, because it leaves symbols unchanged. The basic palindrome program compares every character, so use the cleaned-up version (Method 4) to ignore spaces and punctuation.
What is the time complexity of these programs?
Both programs take O(n) time for a string of n characters. The palindrome program does at most n ÷ 2 comparisons.