split() String 클래스의 메소드 주어진 정규 표현식의 일치를 중심으로 현재 문자열을 분할합니다. 이 메서드에서 반환된 배열에는 주어진 표현식과 일치하는 다른 하위 문자열로 종료되거나 문자열의 끝으로 끝나는 이 문자열의 각 하위 문자열이 포함됩니다.
replaceAll() String 클래스의 메소드는 정규 표현식과 교체 문자열을 나타내는 두 개의 문자열을 받아들이고 일치하는 값을 주어진 문자열로 바꿉니다.
특정 단어를 제외한 파일의 모든 문자를 '#'으로 바꾸려면(편도) -
-
파일의 내용을 문자열로 읽습니다.
-
빈 StringBuffer 개체를 만듭니다.
-
split()을 사용하여 얻은 문자열을 String 배열로 분할합니다. 방법.
-
획득한 배열을 통과합니다.
-
필요한 단어와 일치하는 요소가 있으면 문자열 버퍼에 추가합니다.
-
나머지 모든 단어의 문자를 '#'으로 바꾸고 StringBuffer 객체에 추가합니다.
-
마지막으로 StingBuffer를 String으로 변환합니다.
예
다음 내용을 포함하는 sample.txt라는 파일이 있다고 가정합니다. -
Hello how are you welcome to Tutorialspoint we provide hundreds of technical tutorials for free.
다음 프로그램은 파일의 내용을 문자열로 읽어서 특정 단어를 제외한 모든 문자를 '#'으로 바꿉니다.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;
public class ReplaceExcept {
public static String fileToString() throws FileNotFoundException {
String filePath = "D://input.txt";
Scanner sc = new Scanner(new File(filePath));
StringBuffer sb = new StringBuffer();
String input;
while (sc.hasNextLine()) {
input = sc.nextLine();
sb.append(input);
}
return sb.toString();
}
public static void main(String args[]) throws FileNotFoundException {
String contents = fileToString();
System.out.println("Contents of the file: \n"+contents);
//Splitting the words
String strArray[] = contents.split(" ");
System.out.println(Arrays.toString(strArray));
StringBuffer buffer = new StringBuffer();
String word = "Tutorialspoint";
for(int i = 0; i < strArray.length; i++) {
if(strArray[i].equals(word)) {
buffer.append(strArray[i]+" ");
} else {
buffer.append(strArray[i].replaceAll(".", "#"));
}
}
String result = buffer.toString();
System.out.println(result);
}
} 출력
Contents of the file: Hello how are you welcome to Tutorialspoint we provide hundreds of technical tutorials for free. [Hello, how, are, you, welcome, to, Tutorialspoint, we, provide, hundreds, of, technical, tutorials, for, free.] #######################Tutorialspoint ############################################