执手麦田的咖啡空间  
专注于Java的学习研究
公告
  • 于喧闹网界之中,寻一处僻静之所,与三二好友,品程序、论思想,其乐何融融!
    执手麦田的咖啡馆——在这里关注JAVA的学习研究
日历
<2007年4月>
25262728293031
1234567
891011121314
15161718192021
22232425262728
293012345

导航

留言簿(2)

随笔分类(13)

随笔档案(13)

搜索

  •  

最新评论

阅读排行榜

评论排行榜

 
下面这段程序是我所编的为了检索一段字符中某个字符出现次数的程序。不知道是不是最优化,请各位高手做出指点!
附上程序。

 1import java.io.*;
 2
 3
 4public class Find{
 5public static void main(String [] args) throws IOException
 6{   BufferedReader brd = new BufferedReader(new InputStreamReader(System.in));
 7    int count =0;
 8    int from =0;
 9    
10    System.out.println("请输入一句话");
11    String str=brd.readLine(); 
12    System.out.println("请输入要查找的词");
13    String a=brd.readLine();  //a表示待查找的内容
14    String str1=str.toLowerCase();
15    String a1 = a.toLowerCase();
16   //以上两句话的意思是将原文与待查找的字母全部小写,以便查找。
17for (int s=0;s>-1; )
18    {
19    s=str1.indexOf(a1,from);
20    if(s==-1)
21        {
22        System.out.println("查找结束");
23        break;
24        }

25    count++;
26    System.out.println("这是第"+count+"个,它的位置在第"+(s+1)+"个字符处");
27    from=from+s+1;
28  
29        
30
31    }

32System.out.println("一共有"+count+"");
33
34}

35}
posted on 2007-04-27 13:37 执手麦田 阅读(1698) 评论(1)  编辑  收藏 所属分类: 咖啡馆
评论:
  • # re: 检索字符的程序  王凌华 Posted @ 2007-04-27 14:05
    程序写的很精巧,修改一下你的for循环:

    for (int s = 0; s > -1;) {
    if ("".equals(a1)) {
    System.out.println("查询字符不能为空!");
    break;
    } else {
    s = str1.indexOf(a1, from);
    if (s == -1) {
    System.out.println("查找结束");
    break;
    }
    count++;
    System.out.println("这是第" + count + "个,它的位置在第" + (s + 1)
    + "个字符处");
    from = from + s + 1;
    }

    }  回复  更多评论   


只有注册用户登录后才能发表评论。


网站导航:
 
 
Copyright © 执手麦田 Powered by: 博客园 模板提供:沪江博客