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中編寫一個程序,將文件中的所有字元替換為'#”,除了特定的單字的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本文討論了使用Maven和Gradle進行Java項目管理,構建自動化和依賴性解決方案,以比較其方法和優化策略。

本文使用Maven和Gradle之類的工具討論了具有適當的版本控制和依賴關係管理的自定義Java庫(JAR文件)的創建和使用。

本文討論了使用咖啡因和Guava緩存在Java中實施多層緩存以提高應用程序性能。它涵蓋設置,集成和績效優勢,以及配置和驅逐政策管理最佳PRA

本文討論了使用JPA進行對象相關映射,並具有高級功能,例如緩存和懶惰加載。它涵蓋了設置,實體映射和優化性能的最佳實踐,同時突出潛在的陷阱。[159個字符]

Java的類上載涉及使用帶有引導,擴展程序和應用程序類負載器的分層系統加載,鏈接和初始化類。父代授權模型確保首先加載核心類別,從而影響自定義類LOA


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

Dreamweaver CS6
視覺化網頁開發工具

Safe Exam Browser
Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

SublimeText3 Linux新版
SublimeText3 Linux最新版

MantisBT
Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

WebStorm Mac版
好用的JavaScript開發工具