一、题目描述
给定一个字符串,你需要反转字符串中每个单词的字符顺序,同时仍保留空格和单词的初始顺序。
示例:
输入:“Let’s take LeetCode contest”
输出:“s’teL ekat edoCteeL tsetnoc”
提示:
在字符串中,每个单词由单个空格分隔,并且字符串中不会有任何额外的空格。
二、题目答案
class Solution {
public String reverseWords(String s) {
String words[] = s.split(" ");
StringBuilder str = new StringBuilder();
for(String word : words)
str.append(new StringBuilder(word).reverse().toString() + " ");
return str.toString().strip();
}
}
三、题目解析
1.split()
public String[] split(String regex)
Splits this string around matches of the given regular expression.
This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.
The string “boo:and:foo”, for example, yields the following results with these expressions:
Regex | Result |
---|---|
: | { “boo”, “and”, “foo” } |
o | { “b”, “”, “:and:f” } |
Parameters:
regex - the delimiting regular expression
Returns:
the array of strings computed by splitting this string around matches of the given regular expression
Throws:
PatternSyntaxException - if the regular expression’s syntax is invalid
Since:
1.4
See Also:
Pattern
我们这儿使用split来分隔空号,然后将分隔后的字符串一次存入words[]。
2.StringBuilder() or StringBuffer()
StringBuilder类在Java5中引入。这个类的前身是StringBuffer,它的效率稍微低些,但是允许采用多线程的方式添加和删除字符。如果所有字符串编辑操作都是在单线程中执行的,则应该使用StringBuilder。
3.toString()
toString()返回一个与构建器StringBuilder或缓冲器StringBuffer内容相同的字符串。
4.strip()
返回一个新的字符串。这个字符串将删除原始字符串头部和尾部的空格。
当然也可以采用trim(),此时将会删除原始字符串头部和尾部小于等于U+0020的字符。