Top 10 Intermediate Java StringBuilder Programs
1. Reverse Each Word in a Sentence
Input: "Hello World"
Output: "olleH dlroW"
Code:
String[] words = str.split(" ");
StringBuilder result = new StringBuilder();
for (String word : words) {
result.append(new StringBuilder(word).reverse()).append(" ");
}
return result.toString().trim();
2. Compress a String (Run-Length Encoding)
Input: "aaabbc"
Output: "a3b2c1"
Code:
StringBuilder sb = new StringBuilder();
int count = 1;
for (int i = 1; i <= s.length(); i++) {
if (i == s.length() || s.charAt(i) != s.charAt(i - 1)) {
sb.append(s.charAt(i - 1)).append(count);
count = 1;
} else {
count++;
}
}
return sb.toString();
3. Remove Consecutive Duplicates
Input: "aaabbccdaa"
Output: "abcda"
Code:
StringBuilder sb = new StringBuilder();
sb.append(s.charAt(0));
for (int i = 1; i < s.length(); i++) {
if (s.charAt(i) != s.charAt(i - 1)) {
sb.append(s.charAt(i));
}
}
return sb.toString();
4. Check if Two Strings are Anagrams Using StringBuilder
Input: "listen", "silent"
Output: true
Code:
if (s1.length() != s2.length()) return false;
StringBuilder sb = new StringBuilder(s2);
for (char c : s1.toCharArray()) {
Top 10 Intermediate Java StringBuilder Programs
int index = sb.indexOf(String.valueOf(c));
if (index == -1) return false;
sb.deleteCharAt(index);
}
return sb.length() == 0;
5. Remove All Occurrences of a Character
Input: "banana", 'a'
Output: "bnn"
Code:
StringBuilder sb = new StringBuilder();
for (char ch : str.toCharArray()) {
if (ch != c) sb.append(ch);
}
return sb.toString();
6. Toggle Case of Each Character
Input: "AbC"
Output: "aBc"
Code:
StringBuilder sb = new StringBuilder();
for (char ch : str.toCharArray()) {
if (Character.isUpperCase(ch)) sb.append(Character.toLowerCase(ch));
else sb.append(Character.toUpperCase(ch));
}
return sb.toString();
7. Check for Rotation of a String
Input: "abcd", "cdab"
Output: true
Code:
if (s1.length() != s2.length()) return false;
return (s1 + s1).contains(s2);
8. Build a String from an Array of Integers
Input: [1, 2, 3]
Output: "123"
Code:
StringBuilder sb = new StringBuilder();
for (int num : nums) {
sb.append(num);
}
return sb.toString();
9. Remove Vowels from a String
Input: "education"
Top 10 Intermediate Java StringBuilder Programs
Output: "dctn"
Code:
StringBuilder sb = new StringBuilder();
for (char ch : s.toLowerCase().toCharArray()) {
if ("aeiou".indexOf(ch) == -1) sb.append(ch);
}
return sb.toString();
10. Replace All Spaces with Hyphens
Input: "CS KK is learning"
Output: "CS-KK-is-learning"
Code:
return new StringBuilder(s).toString().replace(" ", "-");