举例如下:
//去掉字串两端空格 trim()
String str = " zh an gsan ";
String trim = str.trim();
System.out.println(trim);//输出去除两端空格的字符串;
几种常见的实例如下:
//去掉中间空格
String str2 = " zh an g s a n ";
String s0="";
String ss2="";
for (int i = 0; i < str2.length(); i++) {
char ch = str2.charAt(i);
if(ch!=' '){
s0= str2.substring(0,str2.indexOf(ch)); //含头不含尾 0 3
break;
}
}
for (int i =str2.length()-1; i>=0;i--) {
char ch = str2.charAt(i);
if (ch != ' ') {
System.out.println(ch+"");
int i1 = str2.lastIndexOf(ch);
ss2=str2.substring(i1+1);
break;
}
}
System.out.println(s0.length());
System.out.println(ss2.length());
String concat = s0.concat(str2.replace(" ", "")).concat(ss2);
System.out.println(concat);
//去掉左端空格
String str3 = " zhangsan ";
String newStr="";
for (int i = 0; i < str3.length(); i++) {
char ch = str3.charAt(i);
if (ch!= ' ') {
newStr=str3.substring(str3.indexOf(ch));
break;
}
}
System.out.println(newStr);