People help please. See, I have a proposal "Mom washed the frame. Dad is a great fellow." And the result should turn out to be the "mom's soap frame. Well done great dad." But according to my code, the first word of the sentence and the last word of the last sentence change.

public static void changing_place(String s) { String[] words = s.split(" ");//Разбиение строки на слова String temp = words[0];//записуем первое слово words[0] = words[words.length - 1];//находим послднее слово words[words.length - 1] = temp;// говорим что бып послденее записалось в первое for (String word : words) {//перебираем и записуем в новую строку System.out.print(word + " ");//выводим } System.out.println(); } 
  • 2
    What code? - PinkTux
  • Just from a mobile is not very convenient. I'll be home throwing code - Vlad Kesia
  • Well, look, judging by your code, you need to change the 3rd and 4th lines and change the 5th and 8th positions. The idea is to display parvilno - JVic
  • That is, I change the conditions and slightly rearrange the code execution order - Vlad Kesya

1 answer 1

 // важно, что в конце точка, а за ней пробел String source = "мама мыла раму. Папа большой молодец. "; String result = source.replaceAll("([^. ]+) ([^.]+) ([^. ]+)\\. ", "$3 $2 $1. "); // result == "раму мыла мама. молодец большой Папа. " 

Consider regular expression details:

([^. ]+) ([^.]+) ([^. ]+)\\.

Each such unit will be responsible for one sentence.
A regular expression consists of three parts:

([^. ]+) , ([^.]+) and ([^. ]+)\\.


The first part ([^. ]+) Is responsible for the first word in the sentence. Record [^. ] [^. ] means "any character except period and space" .

The plus sign repeats the previous character a positive number of times, so the entry [^. ]+ [^. ]+ means "any character except a point and a space, repeated a positive number of times," that is, just the first word of a sentence. We take [^. ]+ [^. ]+ in brackets so that you can refer to the first word of the sentence as $1 in the replacement string (the second argument of the String.replaceAll () function )

  • one
    Very clear and clear. Thank you very much - Vlad Kesya
  • Dmitry is another question [^. ] - this construction is responsible for the preview word and we appeal to it $ 1 to the last word we refer to $ 3. And $ 2 we refer to the word which is in the middle right? - Vlad Kesya
  • Not really, $ 2 is all the words that are between the first and the last. If there are only three words in a sentence, then $ 2 is really responsible for the middle word, but when there are more than three words in the sentence, then $ 2 consists of several words. - diraria
  • Dmitry I understood. And if we have a sentence of 5 words. And I need to change the 5 word to 3. Then I add [^. ] + and $ 4. - Vlad Kesia
  • Yes, you will need to add two pieces [^. ] + (so that at the beginning of the regular season it was [^.] + three times and take the “$ 1 $ 2 $ 5 $ 4 $ 3” replacement line - diraria