A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 张振纲 中级黑马   /  2012-8-29 14:00  /  1212 人查看  /  2 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 张振纲 于 2012-8-29 14:06 编辑
  1. package Exercise;

  2. public class charTime {

  3.         /**
  4.          * @param args
  5.          */
  6.         public static void main(String[] args) {
  7.                 // TODO Auto-generated method stub
  8.                 String s = "    sdjkfljasd    ";                                                     
  9.                 int times = 0;        //定义一个计数器
  10.                 int index = 0;
  11.                 char key ;
  12.                 for (int i = 0; i < s.length(); i++) {
  13.                         key = s.charAt(i);                                  <FONT color=red>获取字符串的第一个字符</FONT>
  14.                         while(s.indexOf(key)!=-1){                      <FONT color=red>然后以这个字符串中有无这个字符为条件循环</FONT><FONT color=red>
  15. </FONT>                                s=s.substring(s.indexOf(key)+1);             <FONT color=red>有就截取后面的字符串,继续查找
  16. </FONT>                                times++;                                                          <FONT color=red> 计数器递增
  17. </FONT>                        }
  18.                         System.out.println("'"+key+"'"+"="+times);
  19.                 }
  20.                
  21.         }

  22. }


  23. <FONT color=red>想让key依次获取字符串中的字符并且去作为key查找次数,怎么实现</FONT>
复制代码

2 个回复

倒序浏览
上面代码中key = s.charAt(i);然后进入while循环,在while循环中找到一个s的(s.indexOf(key)位置,就截取,一直到找不到该位置结束,这样s = "    sdjkfljasd    ",第一个是" ",最后一个也是" "所以s在进入while循环中就截取完了。while外层的for循环就只进一次。所以你的到的key是s的第一个元素" " times查找的次数是s字符串中" "的个数。
回复 使用道具 举报
public class test1 {
        public static void main(String[] args) {
                 String s = "    sdjkfljasd    ";                                                     

         int times = 0;        //定义一个计数器

         int index = 0;

         char key ;

         for (int i = 0; i < s.length(); i++) {

                 key = s.charAt(i);                      //  <FONT color=red>获取字符串的第一个字符</FONT>

                 while(s.indexOf(key)!=-1){               //  <FONT color=red>然后以这个字符串中有无这个字符为条件循环</FONT><FONT color=red></FONT>                             
                         s=s.substring(s.indexOf(key)+1);     //   <FONT color=red>有就截取后面的字符串,继续查找</FONT>            
                         times++;                           //  <FONT color=red> 计数器递增//</FONT>                     
                         }
           System.out.println("'"+key+"'"+"="+times);

         }

}
}
//输出结果:' '=8
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马