1. Introduction: More Than Just Text
Strings are everywhere in programming. From user inputs to storing data, from building web pages to handling commands—strings are the backbone of interaction with computers.
While strings may seem simple—just sequences of characters—mastering string manipulation gives you the power to write more efficient, readable, and robust programs.
In this post, we'll explore essential string operations through practical problems to strengthen your understanding of string handling in Java.
2. Strings in Java: A Quick Refresher
In Java, strings are immutable—once created, their contents cannot be changed. Instead, any operation that modifies a string returns a new string.
Useful things to remember:
- Access characters using
.charAt(index)
- Use
.substring(start, end)
for extracting parts - Prefer
StringBuilder
for dynamic string construction
Understanding these concepts will help you write cleaner and faster Java programs.
3. Problem 1: Palindrome Check
A palindrome is a word or phrase that reads the same forward and backward.
Examples: "madam"
, "racecar"
, "A man, a plan, a canal, Panama"
✅ Approach
- Two-pointer technique: Compare characters from both ends.
- Reverse and compare: Reverse the string and check if it equals the original.
👉 Normalize the string (remove punctuation, spaces, convert to lowercase).
💻 Code
public static boolean isPalindrome(String input) {
String sanitized = input.replaceAll("[^a-zA-Z0-9]", "").toLowerCase();
int left = 0, right = sanitized.length() - 1;
while (left < right) {
if (sanitized.charAt(left) != sanitized.charAt(right)) {
return false;
}
left++;
right--;
}
return true;
}
public static void main(String[] args) {
System.out.println(isPalindrome("Madam")); // true
System.out.println(isPalindrome("Hello")); // false
}
4. Problem 2: Reverse Each Word in a String
Goal: Reverse every word in a sentence, but keep the word order unchanged.
📝 Example:
Input: "Hello World"
Output: "olleH dlroW"
💻 Code
public static String reverseWords(String sentence) {
String[] words = sentence.split(" ");
StringBuilder result = new StringBuilder();
for (String word : words) {
StringBuilder reversed = new StringBuilder(word).reverse();
result.append(reversed).append(" ");
}
return result.toString().trim();
}
public static void main(String[] args) {
System.out.println(reverseWords("Hello World")); // olleH dlroW
}
5. Problem 3: Printing All Substrings
What’s a substring? A contiguous portion of a string.
Example: "ell"
is a substring of "Hello"
.
✅ Approach
Use nested loops with .substring(i, j)
to generate and print all substrings.
💻 Code
public static void printAllSubstrings(String str) {
for (int i = 0; i < str.length(); i++) {
for (int j = i + 1; j <= str.length(); j++) {
System.out.println(str.substring(i, j));
}
}
}
public static void main(String[] args) {
printAllSubstrings("abc");
}
🔽 Output:
a
ab
abc
b
bc
c
6. Problem 4: Remove Consecutive Duplicate Characters
Goal: Remove characters that appear consecutively more than once.
📝 Example:
Input: "aaabbcdeeff"
Output: "abcdef"
💻 Code
public static String removeConsecutiveDuplicates(String input) {
if (input.isEmpty()) return input;
StringBuilder result = new StringBuilder();
char prev = input.charAt(0);
result.append(prev);
for (int i = 1; i < input.length(); i++) {
char curr = input.charAt(i);
if (curr != prev) {
result.append(curr);
}
prev = curr;
}
return result.toString();
}
public static void main(String[] args) {
System.out.println(removeConsecutiveDuplicates("aaabbcdeeff")); // abcdef
}
7. Problem 5: Remove a Specific Character
Goal: Remove all instances of a specific character.
📝 Example:
Input: "programming", remove 'g'
Output: "prorammin"
💻 Code
public static String removeCharacter(String str, char ch) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) != ch) {
result.append(str.charAt(i));
}
}
return result.toString();
}
public static void main(String[] args) {
System.out.println(removeCharacter("programming", 'g')); // prorammin
}
8. Problem 6: Check If Two Strings Are Permutations
Goal: Determine if two strings are permutations (contain the same characters in any order).
📝 Example:
"listen" and "silent" → true
"hello" and "world" → false
✅ Approach
- Sort both strings and compare character arrays.
💻 Code
import java.util.Arrays;
public static boolean arePermutations(String s1, String s2) {
if (s1.length() != s2.length()) return false;
char[] arr1 = s1.toCharArray();
char[] arr2 = s2.toCharArray();
Arrays.sort(arr1);
Arrays.sort(arr2);
return Arrays.equals(arr1, arr2);
}
public static void main(String[] args) {
System.out.println(arePermutations("listen", "silent")); // true
System.out.println(arePermutations("hello", "world")); // false
}
9. Problem 7: String Compression
Goal: Compress a string by replacing repeated characters with the character followed by the count.
Return the original string if the compressed one isn't shorter.
📝 Example:
Input: "aaabbccca"
Output: "a3b2c3a1"
💻 Code
public static String compressString(String input) {
if (input.isEmpty()) return input;
StringBuilder compressed = new StringBuilder();
int count = 1;
for (int i = 1; i <= input.length(); i++) {
if (i < input.length() && input.charAt(i) == input.charAt(i - 1)) {
count++;
} else {
compressed.append(input.charAt(i - 1)).append(count);
count = 1;
}
}
String result = compressed.toString();
return result.length() < input.length() ? result : input;
}
public static void main(String[] args) {
System.out.println(compressString("aaabbccca")); // a3b2c3a1
}
10. Conclusion: The Foundation for Advanced Text Processing
These problems are not just coding exercises—they are the foundation for advanced text processing.
By mastering string operations, you’re preparing yourself to handle:
- File parsing
- Text analysis
- Input validation
- Data transformation
Stay curious and keep practicing!
Top comments (0)