-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathP35_ReverseStringWithoutBuiltIn.java
More file actions
34 lines (29 loc) · 1.12 KB
/
Copy pathP35_ReverseStringWithoutBuiltIn.java
File metadata and controls
34 lines (29 loc) · 1.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package programs;
/**
* ============================================================
* PROGRAM 35: Reverse a String Without Built-in Functions
* ============================================================
* Problem: WAP to reverse a String manually using:
* a) Character array two-pointer swap
* b) StringBuilder manual prepend / backward traversal
* ============================================================
*/
public class P35_ReverseStringWithoutBuiltIn {
public static String reverseWithCharArray(String str) {
if (str == null) return null;
char[] chars = str.toCharArray();
int left = 0, right = chars.length - 1;
while (left < right) {
char temp = chars[left];
chars[left++] = chars[right];
chars[right--] = temp;
}
return new String(chars);
}
public static void main(String[] args) {
String[] words = {"Java", "Antigravity", "racecar", "Hello World 2026"};
for (String w : words) {
System.out.printf(" Original: \"%-18s\" -> Reversed: \"%s\"%n", w, reverseWithCharArray(w));
}
}
}