例如字符串: String str = "    dsadasd gff bgfbf da d asd   ";  //这样一个字符串,前面包含的空格个数不算,中间和最后的空格要算,求总个数
 //这个题目后面包含了3个空格 所以应该是8个空格
希望能有最高效的方法!

解决方案 »

  1.   

    算法道是写了一个.高不高效就不晓得了.public class Test{
    public static void main(String[] args){
    String str = "    dsadasd gff bgfbf da d asd   ";



    int count =  0;
    int flag = 0;
    for (int i = 0; i<str.length(); i++){
    char c = str.charAt(i);
    System.out.println (c);

    if(c!=' ' && flag ==0){
    flag = 1;
    }else if(c==' ' && flag !=0){
    count++;
    }

    }


    System.out.println (count);


    }
    }
      

  2.   


     哎... 这样肯定不行的 我也是用的for+if     老大说这样效率不好阿     您看看能改成正则嘛?
      

  3.   

    一步到位的正则不会,谁有我也想学
    -------------------------------------------------------------------------------------------------------------
    /**
     * 
     */
    package test;/**
     * 
     * @author JHF Team <[email protected]>
     * 
     * 
     * @copyright 2006-2007, BestWiz(Dalian) Co.,Ltd
     */
    public class NullCount {    /**
         * 判断字符中含有空格的个数(前面的空格不算)
         * 
         * @return int
         * @param nu
         * 
         * @author guoqiang <[email protected]>
         */
        public static int isNull(String nu) {        @SuppressWarnings("unused")
            String str = "";
            int count = 0;
            
            for (int i = 0; i < nu.length(); i++) {
                if (!String.valueOf(nu.charAt(i)).matches("\\s")) {
                    str = nu.substring(i, nu.length());
                    break;
                }
            }
            
            for (int j = 0; j < str.length(); j++) {
                if (String.valueOf(str.charAt(j)).matches("\\s")) {
                    count++;
                }
            }
            
            return count;
        }    /**
         * main主函数
         * 
         * @return
         * @param args
         * 
         * @author guoqiang <[email protected]>
         */
        public static void main(String[] args) {        // 判断字符中含有空格的个数(前面的空格不算)
            System.out.println();
            System.out.println("判断字符中含有空格的个数(前面的空格不算)");
            int nu1 = isNull("      a    b   c     d    ");
            System.out.println("nu1: " + nu1);
            int nu2 = isNull("   abcdefg");
            System.out.println("nu2: " + nu2);
        }
    }
    --------------------------------------------------------------------------------------------------------------
      

  4.   

    http://hi.baidu.com/jingleq/blog/item/7bc39b62b61839dce7113a54.html
    看看 正则的效率其实并不高
    其实2楼的方法就可以了