code_junkie

Java Problem: Returning a string entered as reverse text

Nov 14th, 2011
160
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.93 KB | None | 0 0
  1. lastSpace = stringIn.length();
  2.  
  3. for (int i = stringIn.length() - 1; i >= 0; i--){
  4. chIn = stringIn.charAt(i);
  5. if (chIn == ' '){
  6. word = stringIn.substring(i + 1, lastSpace);
  7. stringOut.concat(word);
  8. lastS = i;
  9. }
  10. }
  11. word = stringIn.substring(0,lastSpace);
  12. stringOut.concat(word);
  13.  
  14. return stringOut;
  15.  
  16. stringOut = stringOut.concat(word);
  17.  
  18. stringOut += word
  19.  
  20. public String reverseWords(String words)
  21. {
  22. if(words == null || words.isEmpty() || !words.contains(" "))
  23. return words;
  24.  
  25. String reversed = "";
  26. for(String word : words.split(" "))
  27. reversed = word + " " + reversed;
  28.  
  29. return reversed;
  30. }
  31.  
  32. stringOut=stringOut.concat(word)
  33.  
  34. import java.util.*;
  35.  
  36. class ReverseBuffer {
  37. private StringBuilder soFar;
  38. public ReverseBuffer() {
  39. soFar = new StringBuilder();
  40. }
  41.  
  42. public void add(char ch) {
  43. soFar.append(ch);
  44. }
  45.  
  46. public String getReversedString() {
  47. String str = soFar.toString();
  48. soFar.setLength(0);
  49. return str;
  50. }
  51. }
  52.  
  53. public class Reverso {
  54. public static String[] getReversedWords(String sentence) {
  55. ArrayList &lt String &gt strings = new ArrayList &lt String &gt();
  56. ReverseBuffer rb = new ReverseBuffer();
  57. for(int i = 0;i &lt sentence.length();i++) {
  58. char current = sentence.charAt(i);
  59. if(current == ' ') {
  60. strings.add(rb.getReversedString());
  61. }
  62. else {
  63. rb.add(current);
  64. }
  65. }
  66. strings.add(rb.getReversedString());
  67. Collections.reverse(strings);
  68. return (String[])strings.toArray(new String[0]);
  69. }
  70.  
  71. public static void main(String[] args) {
  72. String cSentence = "The rain in Spain falls mostly on the";
  73. String words[] = Reverso.getReversedWords(cSentence);
  74. for(String word : words) {
  75. System.out.println(word);
  76. }
  77. }
  78. }
Add Comment
Please, Sign In to add comment