-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathStringTest.java
More file actions
55 lines (48 loc) · 1.59 KB
/
StringTest.java
File metadata and controls
55 lines (48 loc) · 1.59 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
public class StringTest {
public static void main(String[] args) {
String str = "My name is khan";
// String result = reverseString(str);
// String result = reverseWords(str);
// String result = reverseSequence(str);
String result = iReverseSequence(str);
System.out.println(result);
}
static String reverseString(String str) {
char[] ch = str.toCharArray();
StringBuilder sb = new StringBuilder();
for (int i=(ch.length-1);i>=0;i--) {
sb.append(ch[i]);
}
return sb.toString();
}
static String reverseWords(String str) {
String[] st = str.split("\\s");
StringBuilder sb = new StringBuilder();
for(int i=0; i < st.length;i++) {
sb.append(reverseString(st[i])+" ");
}
return sb.toString();
}
static String reverseSequence(String str) {
String[] st = str.split("\\s");
StringBuilder sb = new StringBuilder();
for(int i=(st.length-1);i>=0;i--) {
sb.append(st[i]+" ");
}
return sb.toString();
}
// Without using inbuilt java functions (for ex without using split())
// I still used substr() though
static String iReverseSequence(String str) {
String word = "";
int lastIndex = str.length();
for(int i=(str.length()-1);i>=0;i--) {
if(str.charAt(i) == ' ') {
word += str.substring(i+1,lastIndex)+" ";
lastIndex = i;
}
}
word += str.substring(0,lastIndex);
return word;
}
}