1、读取一个文件,并替换其中指定的字符串为特定字符串

import java.io.*;
public class readFile {
	public static void main(String[] args){
		StringBuffer sb = new StringBuffer();
		String text = null;
		BufferedReader br = null;
		String ss = null;
	    File f = new File("d:\\findit.txt");
	    try{
	    	FileInputStream fis = new FileInputStream(f);
	    	InputStreamReader isr = new InputStreamReader(fis);
	    	br = new BufferedReader(isr);
	    	while((text=br.readLine()) != null){
	    		ss = text.replace("abc","123");
	    		sb = sb.append(ss).append(System.getProperty("line.separator"));
	    	}
	    }catch(FileNotFoundException e){
	    	e.printStackTrace();
	    }catch(IOException e){
	    	e.printStackTrace();
	    }finally{
	    	try{
	    		if(br != null)
	    			br.close();
	    	}catch(IOException e){
	    		e.printStackTrace();
	         }
	    }
	     System.out.println(sb.toString());
	     System.out.println("-------------------------------");
	     System.out.println(sb.toString());
	    }
	}

文本替换(如果是指定位置的替换,则用substring分割后再组合、如果是字符的替换,可以用replace(待替换的、被替换的)或者replaceAll(正则表达式、被替换的字符串)、如果是先查找再替换。)

先读取到StringBuffer中,再查找,再替换。

例如,读取文本test.txt并把其中所有的abc替换为123,要求完全匹配才替换,如abcd就不能替换。怎样实现?以上程序没有实现完全匹配的要求。

如果要求不用库函数,自己写出替换部分的代码呢?看下模式匹配算法KMP。


你可能感兴趣的:(面试题)