-
Notifications
You must be signed in to change notification settings - Fork 50
Expand file tree
/
Copy pathReverseSentenceExample.java
More file actions
54 lines (38 loc) · 1.27 KB
/
ReverseSentenceExample.java
File metadata and controls
54 lines (38 loc) · 1.27 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
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
class Main {
// Method to reverse a string
public static String reversingMethod(String str) {
// if the string is null or empty
if (str == null || str.equals("")) {
return str;
}
// create a list of characters
List<Character> sentenceIntoCharList = new ArrayList<Character>();
// push every character of the given string into it
for (char oneCharactorOfTheSentence : str.toCharArray()) {
sentenceIntoCharList.add(oneCharactorOfTheSentence);
}
// reverse list using java Collection API
Collections.reverse(sentenceIntoCharList);
// convert List into string
StringBuilder builder = new StringBuilder(sentenceIntoCharList.size());
for (Character c : sentenceIntoCharList) {
builder.append(c);
}
return builder.toString();
}
public static void main(String[] args) {
System.out.println("Plz enter something to reverse: ");
// input of the sentence
Scanner scanner = new Scanner(System.in);
String inputString = scanner.nextLine();
// String is immutable
String reversedInputString = reversingMethod(inputString);
System.out.println(
"\n***********************\nThe reversed sentence of \' " + inputString + " \' is: " + reversedInputString);
scanner.close();
}
}