Java字符串去中间空格
字符串两边有空格则可以用str.trim()去除
但中间有空格怎么去除?
方法一:遇到空格跳过
package com.jingfei.csdn;
public class Demo1 {
//去除字符串中的空格
public static void main(String[] args) {
String str = "hello world ! 123 我爱 你 ";
String str1="";//定义一个空串
for (int i = 0; i < str.length(); i++) {
if(str.charAt(i)==' '){
continue;
}else{
str1+=str.charAt(i);
}
}
//System.out.println(str);
System.out.println(str1);
}
}
hello world ! 123 我爱 你
helloworld!123我爱你
Process finished with exit code 0
方法二:replace
package com.jingfei.csdn;
public class Demo1 {
//去除字符串中的空格
public static void main(String[] args) {
String str = "hello world ! 123 我爱 你 ";
System.out.println(str);
String replace = str.replace(" ", "");
System.out.println(replace);
}
}
hello world ! 123 我爱 你
helloworld!123我爱你
Process finished with exit code 0
repalce方法是将里面的所有小串替换为你给定的.
当然也可以用循环,str.indexOf(’ ')=-1跳出
方法三:递归
写着玩,锻炼递归思维
package com.jingfei.csdn;
public class DemoDiGui {
public static void main(String[] args) {
String str = " hello world ! 123 我爱 你";
System.out.println(str);
String s = strDemo(str);
System.out.println(s);
}
private static String strDemo(String str) {
if(str.indexOf(" ")==-1){
//当str中无空格时(即==-1)返回最后一段的str
return str;
}else {
//return str.substring(0,str.indexOf(" "))+strDemo(str.substring(str.indexOf(" ")).trim());
return str.substring(0,str.indexOf(" ")).concat(strDemo(str.substring(str.indexOf(" ")).trim()));
//前一段无空格的字符串拼上,对后一段含有空格的字符串先trim()去空格后传入方法递归
//用concat拼接效率好一点,结果都一样
}
}
}
hello world ! 123 我爱 你
helloworld!123我爱你
Process finished with exit code 0
谢谢!