Write A Program To Toggle Each Character In A String In Java
This article explores various methods to toggle the case of each character within a string in Java. You will learn how to efficiently convert uppercase letters to lowercase and lowercase letters to uppercase, leaving other characters unchanged.
Problem Statement
The task is to transform a given string by changing the case of every alphabetical character. If a character is uppercase, it should become lowercase, and if it's lowercase, it should become uppercase. Non-alphabetical characters (numbers, symbols, spaces) should remain in their original form. This is a common string manipulation problem encountered in data processing and text utility development.
Example
Consider the input string: "Hello World 123!"
The desired toggled output would be: "hELLO wORLD 123!"
Background & Knowledge Prerequisites
To understand the solutions presented, a basic understanding of the following Java concepts is beneficial:
- Strings: Immutability, converting to character arrays, and building new strings.
- Characters: ASCII values, methods for case checking and conversion (
Character.isUpperCase(),Character.isLowerCase(),Character.toLowerCase(),Character.toUpperCase()). - Loops:
forloops for iterating over characters. - Conditional Statements:
if-elsefor decision-making. - StringBuilder: For efficient string manipulation.
- Java Streams (Optional): For a more functional approach.
Use Cases or Case Studies
Toggling character cases can be useful in several scenarios:
- Text Formatting: Creating specific text styles, like "Spongebob Case" (alternating case).
- Password Masking/Obscuring: A simple method to transform sensitive data for display without revealing the original case, or for generating variations.
- Data Normalization: Preparing data for case-insensitive comparisons or transforming input into a required format.
- Challenge/Puzzle Solving: Often a component in coding challenges related to string manipulation.
- Unique Identifier Generation: Modifying existing identifiers to create new, distinct ones while retaining some original structure.
Solution Approaches
Here are three distinct approaches to toggle each character in a string in Java.
Approach 1: Using Character Class Methods
This approach leverages Java's built-in Character class methods, which provide a clear and readable way to check and change character cases.
Summary: Iterate through the string, check each character's case using Character.isUpperCase() or Character.isLowerCase(), and then convert it using Character.toLowerCase() or Character.toUpperCase().
// Toggle Case Using Character Methods
// No specific imports needed for basic Character operations within the same package.
// If using specific utilities like Scanner, import java.util.Scanner;
import java.util.Scanner; // Example import, not strictly needed for this program alone
public class Main {
public static void main(String[] args) {
// Step 1: Define the input string
String inputString = "Hello World 123!";
System.out.println("Original String: " + inputString);
// Step 2: Initialize a StringBuilder to build the toggled string
StringBuilder toggledStringBuilder = new StringBuilder();
// Step 3: Iterate through each character of the input string
for (char ch : inputString.toCharArray()) {
// Step 4: Check if the character is an uppercase letter
if (Character.isUpperCase(ch)) {
// Step 5: Convert uppercase to lowercase and append
toggledStringBuilder.append(Character.toLowerCase(ch));
}
// Step 6: Else, check if the character is a lowercase letter
else if (Character.isLowerCase(ch)) {
// Step 7: Convert lowercase to uppercase and append
toggledStringBuilder.append(Character.toUpperCase(ch));
}
// Step 8: If not a letter, append the character as is
else {
toggledStringBuilder.append(ch);
}
}
// Step 9: Convert StringBuilder to String and print the result
String toggledString = toggledStringBuilder.toString();
System.out.println("Toggled String: " + toggledString);
// Example with user input (optional)
// Scanner scanner = new Scanner(System.in);
// System.out.print("\\nEnter another string to toggle: ");
// String userInput = scanner.nextLine();
// StringBuilder userToggled = new StringBuilder();
// for (char ch : userInput.toCharArray()) {
// if (Character.isUpperCase(ch)) {
// userToggled.append(Character.toLowerCase(ch));
// } else if (Character.isLowerCase(ch)) {
// userToggled.append(Character.toUpperCase(ch));
// } else {
// userToggled.append(ch);
// }
// }
// System.out.println("User Toggled String: " + userToggled.toString());
// scanner.close();
}
}
Sample Output:
Original String: Hello World 123!
Toggled String: hELLO wORLD 123!
Stepwise Explanation:
- A
StringBuilderis initialized to efficiently construct the new string, avoiding the overhead of creating many intermediateStringobjects due to their immutability. - The input string is converted into a character array using
toCharArray()for easy iteration. - A
for-eachloop processes eachcharin the array. - Inside the loop,
Character.isUpperCase(ch)checks if the character is an uppercase letter. If true,Character.toLowerCase(ch)converts it to lowercase. - If not uppercase,
Character.isLowerCase(ch)checks if it's a lowercase letter. If true,Character.toUpperCase(ch)converts it to uppercase. - If the character is neither uppercase nor lowercase (e.g., digit, symbol, space), it is appended to the
StringBuilderwithout modification. - Finally,
toggledStringBuilder.toString()converts theStringBuildercontent back into aString, which is then printed.
Approach 2: Using ASCII Values (Bitwise XOR)
This method relies on the fact that uppercase and lowercase English letters have a consistent difference in their ASCII (or Unicode) values. Specifically, the 6th bit (value 32) differentiates between them.
Summary: Iterate through the string. For each alphabetical character, perform a bitwise XOR operation with 32 (0x20) to toggle its case. Non-alphabetical characters remain untouched.
// Toggle Case Using ASCII Values
public class Main {
public static void main(String[] args) {
// Step 1: Define the input string
String inputString = "Programming IS Fun!";
System.out.println("Original String: " + inputString);
// Step 2: Initialize a StringBuilder
StringBuilder toggledStringBuilder = new StringBuilder();
// Step 3: Iterate through each character
for (char ch : inputString.toCharArray()) {
// Step 4: Check if the character is an English alphabet letter
if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) {
// Step 5: Toggle case using XOR with 32 (or 0x20)
// 'A' (65) ^ 32 = 'a' (97)
// 'a' (97) ^ 32 = 'A' (65)
toggledStringBuilder.append((char) (ch ^ 32));
}
// Step 6: If not an alphabet, append as is
else {
toggledStringBuilder.append(ch);
}
}
// Step 7: Print the result
String toggledString = toggledStringBuilder.toString();
System.out.println("Toggled String: " + toggledString);
}
}
Sample Output:
Original String: Programming IS Fun!
Toggled String: pROGRAMMING is fUN!
Stepwise Explanation:
- A
StringBuilderis used for efficient string construction. - The code iterates through each character of the input string.
- An
ifcondition checks if the current characterchfalls within the ASCII ranges for uppercase ('A'-'Z') or lowercase ('a'-'z') English letters. - If it's an English alphabet character, a bitwise XOR operation (
^) with 32 (which is00100000in binary) is performed. This effectively flips the 6th bit, which is the only bit that differs between an uppercase and its corresponding lowercase character in ASCII. The result is then cast back tochar. - If the character is not an English alphabet, it is appended to the
StringBuilderwithout modification. - The final toggled string is obtained and printed.
Approach 3: Using Java Streams (Java 8+)
For more concise and functional-style programming, Java Streams provide an elegant way to transform strings.
Summary: Convert the string to a stream of characters, map each character to its toggled form using Character methods (or ASCII manipulation), and then collect the results into a new string.
// Toggle Case Using Java Streams
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
// Step 1: Define the input string
String inputString = "Java Stream Power!";
System.out.println("Original String: " + inputString);
// Step 2: Convert the string to an IntStream of character codes
String toggledString = inputString.chars()
// Step 3: Map each character code to its toggled version
.map(c -> {
if (Character.isUpperCase(c)) {
return Character.toLowerCase(c);
} else if (Character.isLowerCase(c)) {
return Character.toUpperCase(c);
} else {
return c; // Keep non-alphabetic characters as they are
}
})
// Step 4: Collect the transformed character codes into a new String
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
.toString();
// Step 5: Print the result
System.out.println("Toggled String: " + toggledString);
}
}
Sample Output:
Original String: Java Stream Power!
Toggled String: jAVA sTREAM pOWER!
Stepwise Explanation:
inputString.chars()returns anIntStreamwhere each integer represents a character's Unicode value.- The
map()intermediate operation applies a transformation function to each character code. - Inside the
maplambda, the logic from Approach 1 (Character.isUpperCase(),Character.toLowerCase(), etc.) is used to determine and apply the case toggle. The transformed character code is returned. collect()is a terminal operation that gathers the elements of the stream into a new data structure. Here, it collects theintcharacter codes into aStringBuilder.
-
StringBuilder::new: Supplier for creating a newStringBuilder. -
StringBuilder::appendCodePoint: Accumulator for adding eachint(character code) to theStringBuilder. -
StringBuilder::append: Combiner for merging parallelStringBuilderinstances (not directly relevant for single-threaded streams but good practice).
- Finally,
toString()converts theStringBuilderto the desiredString.
Conclusion
Toggling character case in a string can be achieved using various Java constructs. The Character class methods offer the most readable and idiomatic solution, while ASCII manipulation provides an insight into character encoding and can be slightly more performant for basic ASCII characters. For modern Java development and a more functional style, Streams present a concise and powerful alternative. The choice of method often depends on project readability standards, performance requirements, and the target Java version.
Summary
- Problem: Convert uppercase characters to lowercase and vice-versa in a string, preserving other characters.
- Approach 1 (
CharacterMethods): - Uses
Character.isUpperCase(),Character.isLowerCase(),Character.toLowerCase(),Character.toUpperCase(). - Highly readable and robust for all Unicode characters.
- Approach 2 (ASCII Values / Bitwise XOR):
- Leverages
ch ^ 32for English alphabet characters. - Potentially faster due to bitwise operation.
- Requires explicit range checks (
'a'...'z','A'...'Z'). - Approach 3 (Java Streams):
- Functional approach using
inputString.chars().map().collect(). - Concise and expressive for modern Java.
-
StringBuilderis recommended for all approaches for efficient string concatenation.