Computer >> 컴퓨터 >  >> 프로그램 작성 >> Java

Java에서 String에 하위 문자열(대소문자 무시)이 포함되어 있는지 어떻게 확인합니까?

<시간/>

포함() String 클래스의 메소드는 Sting 값을 매개변수로 받아 현재 String 객체에 지정된 String이 포함되어 있는지 확인하고 포함되어 있으면 true를 반환합니다(그렇지 않으면 false).

toLoweCase() String 클래스의 메소드는 현재 String의 모든 문자를 소문자로 변환하여 반환합니다.

대소문자에 관계없이 문자열에 특정 하위 문자열이 포함되어 있는지 확인하려면 -

  • 문자열을 가져옵니다.

  • 하위 문자열을 가져옵니다.

  • toLowerCase() 메서드를 사용하여 문자열 값을 소문자로 변환하여 fileContents로 저장합니다.

  • toLowerCase() 메서드를 사용하여 문자열 값을 소문자로 변환하여 subString으로 저장합니다.

  • contains() 호출 subString을 매개변수로 전달하여 fileContents에 대한 메서드입니다.

D 디렉토리에 다음 내용이 포함된 sample.txt라는 파일이 있다고 가정합니다. -

Tutorials point originated from the idea that there exists a class of readers who respond better to on-line content
and prefer to learn new skills at their own pace from the comforts of their drawing rooms.
At Tutorials point we provide high quality learning-aids for free of cost.

다음 Java 예제는 사용자로부터 하위 문자열을 읽고 파일에 대소문자에 관계없이 지정된 하위 문자열이 포함되어 있는지 확인합니다.

import java.io.File;
import java.util.Scanner;
public class SubStringExample {
   public static String fileToString(String filePath) throws Exception{
      String input = null;
      Scanner sc = new Scanner(new File(filePath));
      StringBuffer sb = new StringBuffer();
      while (sc.hasNextLine()) {
         input = sc.nextLine();
         sb.append(input);
      }
      return sb.toString();
   }
   public static void main(String args[]) throws Exception {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the sub string to be verified: ");
      String subString = sc.next();
      String fileContents = fileToString("D:\\sample.txt");
      //Converting the contents of the file to lower case
      fileContents = fileContents.toLowerCase();
      //Converting the sub string to lower case
      subString = subString.toLowerCase();
      //Verify whether the file contains the given sub String
      boolean result = fileContents.contains(subString);
      if(result) {
         System.out.println("File contains the given sub string.");
      } else {
         System.out.println("File doesnot contain the given sub string.");
      }
   }
}

출력

Enter the sub string to be verified:
comforts of their drawing rooms.
File contains the given sub string.