Last active
August 29, 2015 14:14
-
-
Save dmnugent80/3042845d29593c992528 to your computer and use it in GitHub Desktop.
Reverse Sentence
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.lang.Math; | |
import java.util.*; | |
// our main class becomes a file but the main method is still found | |
public class HelloWorld | |
{ | |
public static void main(String[] args) | |
{ | |
ReverseSentence myObject = new ReverseSentence(); | |
String reversed = myObject.reverseString("Hello,, . , I would, like to reverse. . this. sentence, and another thing. Thank You."); | |
System.out.println(reversed); | |
} | |
} | |
// this will become its own file too (and these can be in any order) | |
public class ReverseSentence | |
{ | |
public String reverseString(String sentence) | |
{ | |
StringBuffer output = new StringBuffer(); | |
HashMap<Integer, Character> punctMap = new HashMap<Integer, Character>(); | |
for (int i=0; i<sentence.length(); i++){ | |
if (sentence.charAt(i) == ',' || sentence.charAt(i) == '.' || sentence.charAt(i) == ' '){ | |
punctMap.put(sentence.length() - i - 1, sentence.charAt(i)); | |
System.out.println(sentence.length() - i - 1 + " char: " + sentence.charAt(i)); | |
} | |
} | |
String[] arrWords = sentence.split("([ ,.]+)"); | |
for (int j=arrWords.length - 1; j >= 0; j--){ | |
while (punctMap.get(output.length()) != null){ | |
output.append(punctMap.get(output.length())); | |
} | |
output.append(arrWords[j]); | |
System.out.println(arrWords[j]); | |
} | |
return output.toString(); | |
} | |
} | |
/*Output: | |
87 char: , | |
86 char: , | |
85 char: | |
84 char: . | |
83 char: | |
82 char: , | |
81 char: | |
79 char: | |
73 char: , | |
72 char: | |
67 char: | |
64 char: | |
56 char: . | |
55 char: | |
54 char: . | |
53 char: | |
52 char: | |
51 char: | |
50 char: | |
49 char: | |
48 char: | |
43 char: . | |
42 char: | |
33 char: , | |
32 char: | |
28 char: | |
20 char: | |
14 char: . | |
13 char: | |
12 char: | |
6 char: | |
5 char: | |
4 char: | |
0 char: . | |
You | |
Thank | |
thing | |
another | |
and | |
sentence | |
this | |
reverse | |
to | |
like | |
would | |
I | |
Hello | |
.You Thank .thing another and ,sentence .this . .reverse to like ,would I , . ,,Hello | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment