Search code examples
javaandroidregextextutils

Split Strings based on white spaces


(The title may be misleading. I always though the hard part is finding the proper title :D)

Well, sentences are just (long) strings. I want to display these sentences but in a reversed way. Example: "StackOverflow is a community of awesome programmers" would become "programmers awesome of community a is StackOverflow".

So my idea is to have a delimiter, here a blank space. Whenever texts are entered and the space bar pressed, save that word in a list, an ArrayList and then just display them in inverted order in a textView.

So far i can only output texts but without blank spaces (programmersawesomeofcommunityaisStackOverflow) and only using a button. I use the below code to do that:

@Override
        public void onClick(View v) {
            String[] sentence = input.getText().toString().split(" "); //This split() method is the culprit!
            ArrayList<String> wordArray = new ArrayList<>();
            for (String word : sentence) {
                    wordArray.add(word);
            }
            Collections.sort(wordArray);
            StringBuilder invertedSentence = new StringBuilder();
            for (int i = wordArray.size(); i > 0; i--) {
                invertedSentence.append(wordArray.get(i - 1));
            }
            output.setText(invertedSentence.toString());
        }
    });

How can I have a sentence be saved (automatically) in a list as split words when the system detect a white space? And add blank spaces in the output sentences?

Thanks for your time.


Solution

  • Many of the comments have good suggestions, but here is one approach you could use:

        String[] sentence = new String("StackOverflow is a community of awesome programmers").split(" ");
        ArrayList<String> wordArray = new ArrayList<>();
        for (String word : sentence) {
           wordArray.add(0, word);
        }
    
        String backwards = String.join(" ", wordArray);
        System.out.println(backwards);
    

    Output

    programmers awesome of community a is StackOverflow