Bài tập này sẽ hướng dẫn cách sử dụng các phương thức tìm kiếm bằng index trong ngôn ngữ lập trình java. Có 2 phương thức tìm kiếm là indexof() và lastIndexOf().
SearchStringWithIndexOf.java
/**
* @(#)SearchStringWithIndexOf.java
*
* SearchStringWithIndexOf application
*
* @author Bui Ngoc Son
* @version 1.00 2013/10/21
*/
public class SearchStringWithIndexOf
{
public static void main(String[] args)
{
// Khởi tạo đối tượng String
// Declare a String object.
String strOrig = "JAVA Ngon ngu lap trinh, toi dang hoc JAVA.";
/*
* Để tìm kiếm một từ hay nhiều từ ghép lại trong một văn bảng thì ta sử dụng phương thức indexOf, lasindexof.
* Nếu tìm thấy thì nó sẽ trả về vị trí của từ trong vă bản.
* Nếu không tìm thấy thì nó trả về -1.
*
*/
int intIndex = strOrig.indexOf("JAVA");
if (intIndex == - 1)
{
System.out.println("'JAVA' khong tim thay!");
//System.out.println("'JAVA' not found!");
}
else
{
System.out.println("Vi trí dau tien 'JAVA' duoc tim thay la: " + intIndex);
//System.out.println("Found Hello at index: " + intIndex);
}
int positionIndex = strOrig.indexOf("JAVA", 10);
System.out.println("Vi tri cua 'JAVA' duoc tim thay sau vi tri thu 10 la: " + positionIndex);
//System.out.println("Index of JAVA after 11 is " + positionIndex);
int lastIndex = strOrig.lastIndexOf("Hello");
System.out.println("Vi tri cuoi cung cua tu 'JAVA' duoc tim thay la: " + lastIndex);
//System.out.println("Last occurrence of Hello is at index: " + lastIndex);
}
}
* @(#)SearchStringWithIndexOf.java
*
* SearchStringWithIndexOf application
*
* @author Bui Ngoc Son
* @version 1.00 2013/10/21
*/
public class SearchStringWithIndexOf
{
public static void main(String[] args)
{
// Khởi tạo đối tượng String
// Declare a String object.
String strOrig = "JAVA Ngon ngu lap trinh, toi dang hoc JAVA.";
/*
* Để tìm kiếm một từ hay nhiều từ ghép lại trong một văn bảng thì ta sử dụng phương thức indexOf, lasindexof.
* Nếu tìm thấy thì nó sẽ trả về vị trí của từ trong vă bản.
* Nếu không tìm thấy thì nó trả về -1.
*
*/
int intIndex = strOrig.indexOf("JAVA");
if (intIndex == - 1)
{
System.out.println("'JAVA' khong tim thay!");
//System.out.println("'JAVA' not found!");
}
else
{
System.out.println("Vi trí dau tien 'JAVA' duoc tim thay la: " + intIndex);
//System.out.println("Found Hello at index: " + intIndex);
}
int positionIndex = strOrig.indexOf("JAVA", 10);
System.out.println("Vi tri cua 'JAVA' duoc tim thay sau vi tri thu 10 la: " + positionIndex);
//System.out.println("Index of JAVA after 11 is " + positionIndex);
int lastIndex = strOrig.lastIndexOf("Hello");
System.out.println("Vi tri cuoi cung cua tu 'JAVA' duoc tim thay la: " + lastIndex);
//System.out.println("Last occurrence of Hello is at index: " + lastIndex);
}
}
Sau khi chạy chương trình bạn sẽ thấy kết quả như hình bên dưới:
No comments:
Post a Comment