String类的split()方法。将当前字符串拆分为给定正则表达式的匹配项。此方法返回的数组包含此字符串的每个子字符串,该子字符串由与给定表达式匹配的另一个子字符串终止或以字符串末尾终止。
replaceAll() String 类的方法接受两个表示正则表达式的字符串和一个替换字符串,并用给定的字符串替换匹配的值。
用“#”替换文件中除特定单词之外的所有字符(一种方式)-
将文件的内容读取到字符串中。
创建一个空的StringBuffer 对象。
使用 split() 方法将获取的字符串拆分为 String 数组。
遍历得到的数组。
如果其中有任何元素与所需的单词匹配,则将其追加到 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 ############################################
Java 函数式编程范式与面向对象编程范式的比较
Spring Boot项目启动Jar包冲突,如何快速排查并解决?
子类如何通过父类方法修改父类私有属性?
在Java编程中,如果你想在检测到学生ID重复时停止后续代码的执行,可以使用return语句或者抛出异常来实现。以下是两种常见的方法:方法一:使用return语句这种方法适用于在方法内部检测到重复ID时,直接返回,停止后续代码的执行。public void processStudent(Student student) { if (isStudentIdDuplicate(student.getId())) { System.out.println("学生ID已存在,停止处理。")
在 Android Fragment 中,如何最佳地调用 Activity 方法?
HttpServletResponseWrapper加密接口返回值时如何避免中文乱码?