-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSentenceReverse.java
More file actions
77 lines (58 loc) · 1.32 KB
/
SentenceReverse.java
File metadata and controls
77 lines (58 loc) · 1.32 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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package poorvatutorial;
public class SentenceReverse {
// using single counter.
// start is staring index
// end is end index +1.
public static void ReverseString(char[] c,int start, int end)
{
char temp = 0;
int n = end - start ;
for( int i = 0; i < n/2; i++)
{
temp = c[start + i];
c[start + i] = c[end-1-i];
c[end-1-i] = temp;
}
}
// using two counters. start is starting index. End is end index.
public static void ReverseString1(char[] c,int start, int end)
{ char temp = 0;
while(start<end)
{
temp = c[start];
c[start]=c[end];
c[end]=temp;
start++;
end--;
}
//System.out.println(c);
}
public static void SentenceAlgo(char[] c)
{
int start = 0;
int n = c.length-1;
ReverseString1(c,start,n);
System.out.println(c);
for(int i=0; i<= n+1; i++)
{
if(i == n+1)
{
ReverseString1(c,start,i-1);
}
else if(c[i] == ' ')
{
ReverseString1(c,start,i-1);
start = i+1;
}
}
System.out.println("The reverse sentence string is: ");
System.out.println(c);
}
public static void main(String[] args) {
String s = "My name is Poorva";
System.out.println("The original string is: " + s);
char[] c = s.toCharArray();
SentenceAlgo(c);
System.out.println(c);
}
}