Jane F
Jane F

Reputation: 37

How to flip two words in a sentence in java

How to flip two words in a sentence in java like

Input: "hi how are you doing today jane"

Output: "how hi you are today doing jane"

what I tried:

String s = "hi how are you doing today jane";
    ArrayList<String> al = new ArrayList<>();

    String[] splitted = s.split("\\s+");
    int n = splitted.length;
    for(int i=0; i<n; i++) {
        al.add(splitted[i]);
    }
  for(int i=0; i<n-1; i=i+2) {
    System.out.print(al.get(i+1)+" "+al.get(i)+" ");
  }
  if((n%2) != 0) {
          System.out.print(al.get(n - 1));
      }

output I'm getting: "how hiyou aretoday doing"

Upvotes: 2

Views: 303

Answers (3)

Paul Lemarchand
Paul Lemarchand

Reputation: 2096

As you asked to do with only one loop and without extensive use of regex, here is another solution using Collections.swap:

String s = "hi how are you doing today jane";
List<String> splitted = new ArrayList<>(List.of(s.split("\\s+")));

for(int i = 0; i < splitted.size() - 1; i += 2)
    Collections.swap(splitted, i, i + 1);
s = String.join(" ", splitted);
System.out.println(s);

Output:

how hi you are today doing jane

Upvotes: 3

Przemysław Gęsieniec
Przemysław Gęsieniec

Reputation: 648

If you want old-school fori loop and bufor/temp value solution, here you are:

public static void main(String[] args) {
    String s = "hi how are you doing today jane";
    String flip = flip(s);
    System.out.println(flip);
}

private static String flip(String sentence) {

    List<String> words = Arrays.asList(sentence.split("\\s+"));

    for (int i = 0; i < words.size(); i += 2) {
        if (i + 1 < words.size()) {
            String tmp = words.get(i + 1);
            words.set(i + 1, words.get(i));
            words.set(i, tmp);
        }
    }
    return words.stream().map(String::toString).collect(Collectors.joining(" "));
}

However Pauls solultion is way better since it is java, and we are no more in the stone age era :)

Upvotes: 0

Andreas
Andreas

Reputation: 159135

Since you're using split() which takes a regex, it would seem that using regex is a valid solution, so use it:

replaceAll("(\\w+)(\\W+)(\\w+)", "$3$2$1")

Explanation

(\\w+)   Match first word, and capture it as group 1
(\\W+)   Match the characters between the 2 words, and capture them as group 2
(\\w+)   Match second word, and capture it as group 3
$3$2$1   Replace the above with the 3 groups in reverse order

Example

System.out.println("hi how are you doing today jane".replaceAll("(\\w+)(\\W+)(\\w+)", "$3$2$1"));

Output

how hi you are today doing jane

Note: Since your code used split("\\s+"), your definition of a "word" is a sequence of non-whitespace characters. To use that definition of a word, change the regex to:

replaceAll("(\\S+)(\\s+)(\\S+)", "$3$2$1")

Upvotes: 1

Related Questions