java 文本关键字查找功能原理和代码

java 文本关键字查找功能原理和代码java 文本关键字查找功能原理和代码

大家好,又见面了,我是你们的朋友全栈君。

实现原理:

在使用String中indexOf()方法的时候,我们知道如果要是传入一个子字符串作为参数的话类似”from”,则这个方法就返回此”from”子字符串第一次在此字符串中出现的位置,即返回此字符串中第一个”from”子字符串中字符”f”的位置。

  对于此方法忽然有点兴趣,因此我决定查看一下我当前使用的JDK1.7中的源码,其核心代码如下:
    static int indexOf(char[] source, int sourceOffset, int sourceCount,
            char[] target, int targetOffset, int targetCount,
            int fromIndex) {

        ……
        char first = target[targetOffset];
        int max = sourceOffset + (sourceCount – targetCount);

        for (int i = sourceOffset + fromIndex; i <= max; i++) {

            /* 查找子字符串的第一个字符,如果第一个字符都没有出现,则此字符串中不包含这个子字符串 */
            if (source[i] != first) {

                while (++i <= max && source[i] != first);
            }

            /* 查找到第一个字符,则继续查找剩下的字符 */
            if (i <= max) {

                int j = i + 1;
                int end = j + targetCount – 1;
                for (int k = targetOffset + 1; j < end && source[j]
                        == target[k]; j++, k++);

                if (j == end) {

                    /* Found whole string. */
                    return i – sourceOffset;
                }
            }
        }
        return -1;
    }

  如上述代码中我写的注释那样,这个方法首先会查找子字符串的头字符在此字符串中第一次出现的位置,再以此位置的下一个位置作为起始,然后将子字符串的字符(头字符的下一个字符开始)依次和此字符串中字符进行比较,如果全部相等,则返回这个头字符在此字符串中的位置;如果有不相等的,则继续在剩下的字符串中查找这个子字符串的头字符,继续进行上面的过程,直到查找到子字符串或没有找到返回-1为止。

代码:

用JAVA实现对文本文件中的关键字进行搜索, 依据每一行,得到每一行中出现关键词的个数。使用java.io.LineNumberReader.java 进行行读取。示例如下:

一 实现类

[java] 
view plain
 copy

  1. package cn.youzi.test;  
  2.   
  3. import java.io.Closeable;  
  4. import java.io.File;  
  5. import java.io.FileReader;  
  6. import java.io.IOException;  
  7. import java.io.LineNumberReader;  
  8.   
  9. /** 
  10.  * 对文本文件的关键词进行搜索 
  11.  * @author Abel 
  12.  * 
  13.  */  
  14. public class TextFileSearch {  
  15.   
  16.     public void SearchKeyword(File file,String keyword) {  
  17.         //参数校验  
  18.         verifyParam(file, keyword);  
  19.           
  20.         //行读取  
  21.         LineNumberReader lineReader = null;  
  22.         try {  
  23.             lineReader = new LineNumberReader(new FileReader(file));  
  24.             String readLine = null;  
  25.             while((readLine =lineReader.readLine()) != null){  
  26.                 //判断每一行中,出现关键词的次数  
  27.                 int index = 0;  
  28.                 int next = 0;  
  29.                 int times = 0;//出现的次数  
  30.                 //判断次数  
  31.                 while((index = readLine.indexOf(keyword,next)) != –1) {  
  32.                     next = index + keyword.length();  
  33.                     times++;  
  34.                 }  
  35.                 if(times > 0) {  
  36.                     System.out.println(“第”+ lineReader.getLineNumber() +“行” + “出现 “+keyword+” 次数: “+times);  
  37.                 }  
  38.             }  
  39.         } catch (IOException e) {  
  40.             e.printStackTrace();  
  41.         } finally {  
  42.             //关闭流  
  43.             close(lineReader);  
  44.         }  
  45.     }  
  46.   
  47.     /** 
  48.      * 参数校验 
  49.      *  
  50.      * <br> 
  51.      * Date: 2014年11月5日 
  52.      */  
  53.     private void verifyParam(File file, String keyword) {  
  54.         //对参数进行校验证  
  55.         if(file == null ){  
  56.             throw new NullPointerException(“the file is null”);  
  57.         }  
  58.         if(keyword == null || keyword.trim().equals(“”)){  
  59.             throw new NullPointerException(“the keyword is null or \”\” “);  
  60.         }  
  61.           
  62.         if(!file.exists()) {  
  63.             throw new RuntimeException(“the file is not exists”);  
  64.         }  
  65.         //非目录  
  66.         if(file.isDirectory()){  
  67.             throw new RuntimeException(“the file is a directory,not a file”);  
  68.         }  
  69.           
  70.         //可读取  
  71.         if(!file.canRead()) {  
  72.             throw new RuntimeException(“the file can’t read”);  
  73.         }  
  74.     }  
  75.       
  76.     /** 
  77.      * 关闭流 
  78.      * <br> 
  79.      * Date: 2014年11月5日 
  80.      */  
  81.     private void close(Closeable able){  
  82.         if(able != null){  
  83.             try {  
  84.                 able.close();  
  85.             } catch (IOException e) {  
  86.                 e.printStackTrace();  
  87.                 able = null;  
  88.             }  
  89.         }  
  90.     }  
  91.   
  92. }  

二 调用

[java] 
view plain
 copy

  1. package cn.youzi.test;  
  2.   
  3. import java.io.File;  
  4.   
  5. public class TextFileSearchTest {  
  6.   
  7.     public static void main(String[] args) {  
  8.   
  9.         TextFileSearch search = new TextFileSearch();  
  10.         search.SearchKeyword(new File(“E:\\testDir\\news.txt”), “中国”);  
  11.     }  
  12.   
  13. }  



结果 为:

[plain] 
view plain
 copy

  1. 第3行出现 中国 次数: 3  
  2. 第5行出现 中国 次数: 4  
  3. 第7行出现 中国 次数: 1  
  4. 第9行出现 中国 次数: 3  
  5. 第19行出现 中国 次数: 1  
  6. 第34行出现 中国 次数: 1  
  7. 第42行出现 中国 次数: 1  

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/106117.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • html中table居中和表格内容居中的问题

    html中table居中和表格内容居中的问题关于表格中的内容::在表格td中,有两个属性控制居中显示align——表示左右居中——left,center,rightvalign——控制上下居中——left,center,right这两个属性综合使用,就可以让单元格的内容上下左右都居中显示。但是有的时候吧,会失效,那么在td中设置text-align为center也可。td{…

    2022年9月19日
    0
  • Ubuntu 20.04 安装 Docker

    Ubuntu 20.04 安装 Docker检查Ubuntu内核docker需要ubuntu的内核高于3.10uname-rDocker安装#新增更新源sudoecho”debhttps://download.docker.com/linux/ubuntuzestyedge”>/etc/apt/sources.list#step1:安装必要的一些系统工具sudoapt-getupdatesudoapt-get-yinstallapt-transport-httpsca-certi

    2022年7月21日
    13
  • qq刷屏代码如何停止(微信刷屏代码vbs)

    最近有些人向小编反应QQ刷屏代码没办法关,小编认为有必要发布一下关程序的代码,专门针对上次的QQ刷屏代码:sety=getobject(“winmgmts:\\.\root\cimv2”)setx=y.execquery(“select*fromwin32_processwherename=’wscript.exe'”)foreachiinxi.terminat…

    2022年4月17日
    107
  • python-opencv图像处理:sobel算子

    python-opencv图像处理:sobel算子Sobel原理:https://blog.csdn.net/zfjBIT/article/details/86655444函数原型:”’Sobel算子Sobel算子依然是一种过滤器,只是其是带有方向的。在OpenCV-Python中,使用Sobel的算子的函数原型如下:dst=cv2.Sobel(src,ddepth,dx,dy[,dst[,ksize[,s…

    2022年7月14日
    14
  • web激活码【中文破解版】[通俗易懂]

    (web激活码)2021最新分享一个能用的的激活码出来,希望能帮到需要激活的朋友。目前这个是能用的,但是用的人多了之后也会失效,会不定时更新的,大家持续关注此网站~https://javaforall.net/100143.htmlIntelliJ2021最新激活注册码,破解教程可免费永久激活,亲测有效,上面是详细链接哦~DB…

    2022年3月26日
    42
  • 强化学习 模仿学习 于robot[通俗易懂]

    强化学习 模仿学习 于robot[通俗易懂]写在前面:分享知识是再好不过的事情。这篇文章主要是总结自己最近看的一些文章以及相关知识。自己在暑假实习的时候学习的就是在物理仿真平台上做robot的强化学习,未来读PhD的时候也被老师继续分配到了这个方向,哈哈。可能要一直从入门到入土了,趁着最近写researchproposal的时候,将最近的理解记录一下。鉴于笔者知识水平有限,若有不妥当之处,还请指出。摘要:robot强化学习模仿学…

    2022年9月19日
    0

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号