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

Java의 특정 단어에 대해 문자열의 단어를 구문 분석하는 방법은 무엇입니까?

<시간/>

특정 단어에 대한 문자열의 단어를 구문 분석할 수 있는 Java에는 다양한 메소드가 있습니다. 여기서 우리는 그 중 3가지에 대해 논의할 것입니다.

contains() 메소드

String 클래스의 contains() 메서드는 일련의 문자 값을 받아 현재 String에 존재하는지 확인합니다. 찾으면 true를 반환하고 그렇지 않으면 false를 반환합니다.

예시

import java.util.StringTokenizer;
import java.util.regex.Pattern;
public class ParsingForSpecificWord {
   public static void main(String args[]) {
      String str1 = "Hello how are you, welcome to Tutorialspoint";
      String str2 = "Tutorialspoint";
      if (str1.contains(str2)){
         System.out.println("Search successful");
      } else {
         System.out.println("Search not successful");
      }
   }
}

출력

Search successful

indexOf() 메소드

String 클래스의 indexOf() 메서드는 문자열 값을 받아 현재 String에서 그 값의 (시작) 인덱스를 찾아 반환합니다. 이 메서드는 현재 문자열에서 주어진 문자열을 찾지 못하면 -1을 반환합니다.

예시

public class ParsingForSpecificWord {
   public static void main(String args[]) {
      String str1 = "Hello how are you, welcome to Tutorialspoint";
      String str2 = "Tutorialspoint";
      int index = str1.indexOf(str2);
      if (index>0){
         System.out.println("Search successful");
         System.out.println("Index of the word is: "+index);
      } else {
         System.out.println("Search not successful");
      }
   }
}

출력

Search successful
Index of the word is: 30

StringTokenizer 클래스

StringTokenizer 클래스를 사용하면 구분 기호에 따라 문자열을 더 작은 토큰으로 나누고 통과할 수 있습니다. 다음 예제는 소스 문자열의 모든 단어를 토큰화하고 equals()를 사용하여 각 단어를 주어진 단어와 비교합니다. 방법.

예시

import java.util.StringTokenizer;
public class ParsingForSpecificWord {
   public static void main(String args[]) {
      String str1 = "Hello how are you welcome to Tutorialspoint";
      String str2 = "Tutorialspoint";
      //Instantiating the StringTookenizer class
      StringTokenizer tokenizer = new StringTokenizer(str1," ");
      int flag = 0;
      while (tokenizer.hasMoreElements()) {
         String token = tokenizer.nextToken();
         if (token.equals(str2)){
            flag = 1;
         } else {
            flag = 0;
         }
      }
      if(flag==1)
         System.out.println("Search successful");
      else
         System.out.println("Search not successful");
   }
}

출력

Search successful