In this article, we'll delve into a fascinating string manipulation problem that involves swapping corner words of a string and reversing the middle characters. Thisind of problem is qui intergmoncom , and it's a great way to enhance your understanding of string manipulation in Java.
Java提供了豐富的字串操作工具。從基本的拼接和比較操作到更複雜的任務,如字串反轉和交換,Java的String API都可以處理。一個有趣的問題是交換字串的首尾單字並反轉中間字元。這個問題可以透過結合Java內建的String方法和一些手動邏輯來解決。
給定一個字串,我們需要交換第一個和最後一個單詞,並且反轉中間字元的順序,保持字串的第一個和最後一個字元不變。
解決這個問題的策略很簡單 −
Split the input string into words.
交換第一個和最後一個單字。
Reverse the order of the middle characters while keeping the first and last characters of the string in their original positions.
#將單字重新組合成字串。
Below is a Java function that implements the approach described above −
import java.util.*; public class Main { public static String swapAndReverse(String input) { String[] words = input.split(" "); // Swap the first and last words String temp = words[0]; words[0] = words[words.length - 1]; words[words.length - 1] = temp; // Reverse the middle characters of the string, leaving the first and last characters intact for(int i = 0; i < words.length; i++) { if(words[i].length() > 2) { String middleCharacters = words[i].substring(1, words[i].length() - 1); String reversedMiddleCharacters = new StringBuilder(middleCharacters).reverse().toString(); words[i] = words[i].charAt(0) + reversedMiddleCharacters + words[i].charAt(words[i].length() - 1); } } // Join the words back into a string return String.join(" ", words); } public static void main(String[] args) { System.out.println(swapAndReverse("Hello world this is Java")); } }
Jvaa wlrod tihs is Hlleo
讓我們用字串"Hello world this is Java"來測試我們的函式。
The words in the string are ["Hello", "world", "this", "is", "Java"]. After swapping the first and last words, we get ["Java", "world", "this", "is", "Hello"].
Then we reverse the middle characters of each word, excluding the first and last characters, resulting in ["Jvaa", "wlrod", "tihs", "is", "Hlleo"].
最後,我們將單字重新拼接成字串:"Jvaa wlrod tihs is Hlleo"。
所以,swapAndReverse("Hello world this is Java")的輸出是"Jvaa wlrod tihs is Hlleo"。
The swapAndReverse function is working correctly, and it's evident that it's accurately swapping the corner words and reversing the middle characters in the given string. We hope this exampleation clarif the operers in the given string. We hope this exampleation clarif the oper.
Conclusion以上是交換角落的單字並翻轉中間的字符的詳細內容。更多資訊請關注PHP中文網其他相關文章!