字符串trim方法和split方法
trim
用于删除字符串的头尾空白字符串。返回值为String;
public static void main( String[] args ) {
String str = " hello world! ";
System.out.println(str);
System.out.println(str.trim());
}
/**
hello world!
hello world!
*/
split 分割字符串
split(" "):以空格为界限分割字符串。要注意分割出空字符串的情况
@Test
public void test01(){
String str ="a good example";
String[] strs = str.split(" ");
for(String s:strs){
System.out.println("s="+s+";");
}
}
s=a;
s=good;
s=;
s=;
s=example;
实战
剑指 Offer 58 - I. 翻转单词顺序
输入: "the sky is blue"
输出: "blue is sky the";
测试用例:
" hello world! ";
"a good example"
执行用时:1 ms, 在所有 Java 提交中击败了100.00%的用户
内存消耗:38.4 MB, 在所有 Java 提交中击败了28.65%的用户
class Solution {
public String reverseWords(String s) {
//" hello world! "
String[] strs = s.trim().split(" ");
for(int i=0;i<strs.length/2;i++){
String temp =strs[i];
strs[i] = strs[strs.length -i-1];
strs[strs.length -i-1] = temp;
}
StringBuilder sb = new StringBuilder();
for(int i = 0;i<strs.length;i++){
if (strs[i].equals("")) {
continue;
// "a good example"
}
sb.append(strs[i].trim());
if(i!=strs.length-1){
sb.append(" ");
}
}
return sb.toString().trim();
}
}