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. This kind of problem is quite common in coding interviews, and it's a great way to enhance your understanding of string manipulation in Java.
Java提供了丰富的字符串操作工具。从基本的拼接和比较操作到更复杂的任务,如字符串反转和交换,Java的String API都可以处理。一个有趣的问题是交换字符串的首尾单词并反转中间字符。这个问题可以通过结合Java的内置String方法和一些手动逻辑来解决。
Problem Statement
给定一个字符串,我们需要交换第一个和最后一个单词,并且反转中间字符的顺序,保持字符串的第一个和最后一个字符不变。
方法
解决这个问题的策略很简单 −
-
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.
-
将单词重新组合成字符串。
Example
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 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"));
}
}
登录后复制
Output
Jvaa wlrod tihs is Hlleo
登录后复制
Explanation
的中文翻译为:
解释
让我们用字符串"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 example clarifies the operation of the function.
Conclusion
Java offers a wide variety of tools for manipulating strings, making it ideal for solving problems like swapping corner words and reversing middle characters in a string. Mastering these skills will serve you well in both coding interviews and your everyday programming tasks.
以上就是交换角落的单词并翻转中间的字符的详细内容,更多请关注每日运维网(www.mryunwei.com)其它相关文章!