Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

โปรแกรมแทนที่อักขระทั้งหมดในไฟล์ด้วย '#' ยกเว้นคำเฉพาะใน Java


split() วิธีการของคลาสสตริง แยกสตริงปัจจุบันรอบการจับคู่ของนิพจน์ทั่วไปที่กำหนด อาร์เรย์ที่ส่งคืนโดยวิธีนี้ประกอบด้วยสตริงย่อยแต่ละสตริงของสตริงนี้ซึ่งสิ้นสุดโดยสตริงย่อยอื่นที่ตรงกับนิพจน์ที่กำหนดหรือสิ้นสุดที่ส่วนท้ายของสตริง

replaceAll() เมธอดของคลาส String ยอมรับสองสตริงที่แสดงนิพจน์ทั่วไปและสตริงแทนที่ และแทนที่ค่าที่ตรงกันด้วยสตริงที่กำหนด

หากต้องการแทนที่อักขระทั้งหมดในไฟล์ด้วย '#' ยกเว้นคำเฉพาะ (ทางเดียว) -

  • อ่านเนื้อหาของไฟล์เป็นสตริง

  • สร้างวัตถุ StringBuffer ว่าง

  • แยกสตริงที่ได้รับออกเป็นอาร์เรย์ o ของสตริงโดยใช้ split() วิธีการ

  • สำรวจผ่านอาร์เรย์ที่ได้รับ

  • หากองค์ประกอบใดตรงกับคำที่ต้องการ ให้ผนวกเข้ากับบัฟเฟอร์สตริง

  • แทนที่อักขระในคำที่เหลือทั้งหมดด้วย '#' และผนวกเข้ากับวัตถุ 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 ############################################