首页 > 解决方案 > 匹配部分删除,并从一个String中找出一些匹配的关键字

问题描述

我想替换文本文件中存在的字符串中的几个单词。每当建立匹配时,它将删除该匹配。示例:“学习 java 不是那么容易,但 /* 也不是那么难 */ int a, int b, char c”。我需要用它替换整个评论部分和相关单词(/*-- --------*/) 并打印尽可能多的关键字。在这种情况下我应该怎么做?这是我的代码。

public static void main(String[] args)throws IOException 
   {
        File f1=new File("Read_A_File.txt");
        File f2=new File("New_Generated_File.txt");

        FileReader fr=new FileReader(f1);
        FileWriter fw=new FileWriter(f2);

        BufferedReader br=new BufferedReader(fr);
        BufferedWriter bw=new BufferedWriter(fw);

        String st;
        while((st=br.readLine())!=null) 
        {    
         if(st.contains("/*"))
           {
                bw.write(st.replaceAll("([/*-*/])", " "));  
           }

           System.out.println(st);
           bw.newLine();  
        }
        br.close();
        bw.close();
    }

在此处输入图像描述

标签: java

解决方案


编程基础之一。我发现最简单的方法是找到分隔符,然后剪下要保留的部分,然后将它们连接起来。例如:

String str = "word word, /*comment*/ drow drow";
String result;

int start = str.indexOf("/*");
int end = str.indexOf("*/");

result = str.substring(0, start+1)+str.substring(end, str.length()-1);

或者,如果需要,将其放入循环中。首先,您搜索注释开始和结束的索引,然后使用子字符串切出所需的部分。(根据文档, start 是包容性的, end 是排斥性的......),另外,你必须从长度中取反,因为它返回总长度,但 indeces 以 0 开头。这种方法也让嗜血的编程之神高兴.

另一种方法可能是使用 deleteCharAt() 的 for 循环,您只需遍历字符串并逐个删除字符:

for (int i=0; i<end-start; i++) {
 str.deleteCharAt(start);
}

这很好,因为无论语言如何,基本思想都是相同的。第二个也是万无一失的解决方案。


推荐阅读