Java - Làm thế nào nào để tìm một từ trong một chuỗi - How to search for a word inside a string?


Bài viết này tôi sẽ hướng dẫn cách tìm một từ đầu tiên được xuất hiện trong một chuỗi trong ngôn ngữ lập trình Java.





Bài tập - exercises

Tìm từ "car" đầu tiên trong chuỗi "One blue car driving by. Blue car, blue car".


Câu trả lời - Answer

Để tìm một từ đầu tiên trong một chuỗi ta sử dụng phương thức indexOf() của lớp String.


Mã nguồn - Source

/**
 * @(#)FindWord.java
 *
 * FindWord application
 *
 * @author Bui Ngoc Son
 * @website vnlives.net
 * @version 1.00 2014/6/21
 */

public class FindWord {
   
    public static void main(String[] args) {
       
        String str1 = "The cat in the hat.";
        System.out.println(str1);
       
        // find this word
        String str2 = "cat";
       
        int index = str1.indexOf(str2);
       
        if(index >= 0) {
            System.out.println("The word " + str2 + " found index " + index);
            System.out.println("");
        } else {
            System.out.println(str2 + " not found");
        }
       
    }
}


Kết quả - Result







No comments:

Post a Comment