-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReverseString.java
More file actions
40 lines (35 loc) · 918 Bytes
/
ReverseString.java
File metadata and controls
40 lines (35 loc) · 918 Bytes
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
35
36
37
38
39
40
public class ReverseString {
static String s= "My name is Sukanta Sharma.";
static StringBuffer str = new StringBuffer(s);
public static void main(String[] args) {
int i = 0, start = i;
System.out.println("Input String : " + s);
// reverse individual words
while(i < str.length()) {
if (str.charAt(i) == ' ' || i == str.length() - 1) {
if (i == str.length() - 1) { // last character
reverse(start, str.length() - 1);
}
else {
reverse(start, i-1);
start = i + 1;
}
}
i++;
}
System.out.println("Word reverse : " + str);
// reverse the whole string
reverse(0, str.length() - 1);
System.out.println("String reverse : " + str);
}
public static void reverse(int start, int end) {
while (start < end) {
char temp;
temp = str.charAt(start);
str.setCharAt(start, str.charAt(end));
str.setCharAt(end, temp);
start++;
end--;
}
}
}