String Manipulation
String manipulation involves operations like reversing, checking for palindromes, and replacing characters. Since strings are immutable, these operations often create new strings.
1. Reverse a String
public static String reverse(String str) {
return new StringBuilder(str).reverse().toString();
}
// Manual reverse using char array
public static String reverseManual(String str) {
char[] arr = str.toCharArray();
int left = 0, right = arr.length - 1;
while (left < right) {
char temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
left++; right--;
}
return new String(arr);
}
2. Check Palindrome
A palindrome reads the same forwards and backwards.
public static boolean isPalindrome(String str) {
int left = 0, right = str.length() - 1;
while (left < right) {
if (str.charAt(left) != str.charAt(right)) return false;
left++; right--;
}
return true;
}
3. Remove Duplicate Characters
Use a Set to keep track of seen characters.
public static String removeDuplicates(String str) {
Set seen = new LinkedHashSet<>();
for (char c : str.toCharArray()) {
seen.add(c);
}
StringBuilder sb = new StringBuilder();
for (char c : seen) sb.append(c);
return sb.toString();
}
Two Minute Drill
- Reverse string: use StringBuilder.reverse() or two-pointer on char array.
- Palindrome check: two-pointer from ends.
- Remove duplicates: use LinkedHashSet to preserve order.
- Manipulations often require converting to char array or using StringBuilder.
Need more clarification?
Drop us an email at career@quipoinfotech.com
