public class test {
static String username=" a b c ";
public static void main(String[] args) {
System.out.println(username.trim()); }}
怎么去掉开头、结尾和中间的空格????
static String username=" a b c ";
public static void main(String[] args) {
System.out.println(username.trim()); }}
怎么去掉开头、结尾和中间的空格????
int e=0;
StringBuffer result=new StringBuffer();
while((e=username.indexOf(" ",s))>=0){
result.append(username.substring(s,e));
result.append("");
s=e+" ".length();
}
result.append(username.substring(s));
System.out.println(result.toString());
import java.util.regex.Matcher;
import java.util.regex.Pattern;....
.... CharSequence inputstr=" a b c ";
String patternStr=" ";
String replaceStr="";
Pattern pattern=Pattern.compile(patternStr);
Matcher matcher=pattern.matcher(inputstr);
String output=matcher.replaceAll(replaceStr);
System.out.println(output);
或者 username.replaceAll(" ","");
StringBuffer strBuf = new StringBuffer();
String[] arrStr = s.split(" ");
for(int i=0;i<arrStr.length;i++){
if(!arrStr[i].equals("")){
strBuf.append(arrStr[i]);
}
}
return strBuf.toString();
}
或者 username.replaceAll(" ","");
我感觉还是这个来得直接
username.repalaceAl(" +","");
public String trim() {
int first, last;//定义两个变量first和last
first = str.indexOf(' ');//first表示查找到的第一个空格的位置
System.out.println(first);
last = str.lastIndexOf(' ');//last表示查找到的最后一个空格的位置
System.out.println(last);
if (first == -1) {//如果能查找不到空格,则原样输出
System.out.println(str);
} else {//否则执行如下代码
while (first != last) {//至少有两个空格的情况
System.out.println(str = str.substring(0, first) +
str.substring(first + 1, last) +
str.substring(last + 1, str.length()));//将第一个空格和最后一个空格去掉
first = str.indexOf(' ');
System.out.println(first);
last = str.lastIndexOf(' ');
System.out.println(last);
}
if (first != -1) {//如果最后只有一个空格,即first=last且不等于-1,则做如下处理
System.out.print(str = str.substring(0,first)+str.substring(first+1,str.length()));//将唯一一个空格去掉
}
}
return str;
}