java - 匹配部分删除,并从一个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();
}
解决方案
编程基础之一。我发现最简单的方法是找到分隔符,然后剪下要保留的部分,然后将它们连接起来。例如:
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);
}
这很好,因为无论语言如何,基本思想都是相同的。第二个也是万无一失的解决方案。
推荐阅读
- javascript - 如何根据表格单元格值将图标更改为“加号”或“减号”
- typescript - TypeError:无法读取未定义的属性“推送”(将 this.array 传递给回调函数)
- python - 在星形图案内打印?
- c++ - 给定的字符串应该使用递归函数反转
- android - 以编程方式启用移动数据 Android 8.0
- lua - 管理 Lua 5.3 “.0” 行为
- python-3.x - 为什么下面的代码在我的电脑上运行不起来,在在线执行环境下,运行完美。我使用 python 3.7.0
- laravel - 如何在 vuejs 和 vuex 中使用 httponly 标志设置 cookie cookie 来自服务器(Laravel)
- c++ - 在 Qt 4.10.2 中创建 .exe 文件
- assembly - 我如何在实模式下保存一个值并在受保护的情况下访问它?