-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreverseAString.java
More file actions
33 lines (32 loc) · 967 Bytes
/
reverseAString.java
File metadata and controls
33 lines (32 loc) · 967 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
//Question: Reverse each word in a given sentence.
package stringBuilder;
import java.util.Scanner;
public class reverseAString {
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
System.out.print("Enter the string: ");
StringBuilder sb = new StringBuilder(sc.nextLine());
int n = sb.length();
int i = 0, j = 0;
while(j < n) {
if (sb.charAt(j) != ' ') {
j++;
} else {
reverse(sb, i, j-1);
i = j + 1;
j = i;
}
}
reverse(sb, i, j-1);
System.out.print("Final string is: " + sb);
}
public static void reverse(StringBuilder ab, int i, int j) {
char temp;
while(i<j){
temp = ab.charAt(i);
ab.setCharAt(i, ab.charAt(j));
ab.setCharAt(j, temp);
i++; j--;
}
}
}