public class test {
static String username="    a     b     c     ";
public static void main(String[] args) {

System.out.println(username.trim()); }}
怎么去掉开头、结尾和中间的空格????

解决方案 »

  1.   

        int s=0;
        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());
      

  2.   

    另:
    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);
      

  3.   

    直接用 username.replaceAll("\\s","");
    或者 username.replaceAll(" ","");
      

  4.   

    public String mergeSpace(){
    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();
    }
      

  5.   

    直接用 username.replaceAll("\\s","");
    或者 username.replaceAll(" ","");
    我感觉还是这个来得直接
      

  6.   

    以前为了些问题已经讨论过不下20次,但最终还是大家认为别人的做法好:
    username.repalaceAl(" +","");
      

  7.   

    我是新手,自己写了这样一个方法,可以实现替换,大家不要见笑    String str;
        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;
            }