1.给定任意字符串,进行翻转
public String strreverse1(String str){
if (str == null)
return "";
char[] chars = str.toCharArray();
int start = 0, end = chars.length-1;
while(end>start){
char tmp = chars[start];
chars[start] = chars[end];
chars[end] = tmp;
++start;
--end;
}
return new String(chars);
}
2.给定任意字符串,翻转里面的单词
①去除字符串首尾的空格;
②split("\\s+")以正则匹配连续空格分割字符串得到字符数组
③利用StringBuffer将反向拼接字符数组
public String strreverse2(String str){
if (str == null || str.trim().length()==0){
return "";
}
//去除头尾空格后以正则"\\s+"匹配字符串中任意空格进行分割
//arrstr[i]只表示去除空格后的子字符串
String[] arrstr = str.trim().split("\\s+");
StringBuffer sb = new StringBuffer();
for (int i = arrstr.length-1; i>=0; i--){
if (i == 0){
//第0个字符串后不需要加空格
sb.append(arrstr[i]);
}
else{
//其他的后面需要加上空格
sb.append(arrstr[i]+" ");
}
}
return new String(sb);
}