There is a suggestion, for example: "Today is a good day for programming." And in this sentence you need to find the first and last word and swap them.
- What did you try to do and what did you fail to do? - Vartlok
- At first, I ran the whole nozzle before the space and tried to define the word nal then later, of course, it didn’t work either. - Vlad Kesya
- If you were given the correct answer, tick it opposite - it will be useful for those who later stumble on this topic. - Denis
|
2 answers
Use Split to split a line into words (the separator will be a space). Then simply change the first and last elements in the array and output them:
String tmp, s = "Сегодня хороший день для программирования"; String[] words = s.split(" "); tmp = words[0]; words[0] = words[words.length-1]; words[words.length-1] = tmp; for (String word : words) { System.out.print(word + " "); } Conclusion:
programming is a good day for today
If words are separated not only by spaces, but also by commas or semicolon, for example, use regular expressions:
String[] words = s.split("\\W+"); - Thank you, I just started learning Java and there’s really no experience. - Vlad Kesia
- Denis, explain Mozhaluysta this part of words [0] = words [words.length-1]; words [words.length-1] = tmp; - Vlad Kesia
- @VladKesya Memorize the first word, shove the last word there, shove the first word that we remember with the last word. Normal rearrangement of 2 elements of the array. - Denis
|
String str = "Сегодня хороший день для программирования"; String[] words = str.split(" "); String temp = words[words.length - 1]; words[words.length - 1] = words[0]; words[0] = temp; str = Arrays.stream(words).collect(joining(" ")); Break the line into words. In the resulting array, we swap the first and the last element, then we merge it back into a string.
- Artem Can you explain this part of the code String temp = words [words.length - 1]; words [words.length - 1] = words [0]; - Vlad Kesia
- swap items - Artem Konovalov
- See we take the last word and write it in temp. Then we say that the last word would be the first. And the first one with this line is "words [0] = temp;" - Vlad Kesia Nov.
|