溫馨提示×

java字符串查找的形式有哪些

小億
91
2024-03-29 16:31:04
欄目: 編程語言

在Java中字符串查找的形式有以下幾種:

  1. 使用indexOf()方法:該方法返回指定子字符串第一次出現的索引,如果未找到則返回-1。

例如:

String str = "Hello, world!";
int index = str.indexOf("world");
System.out.println(index); // 輸出6
  1. 使用lastIndexOf()方法:該方法返回指定子字符串最后一次出現的索引,如果未找到則返回-1。

例如:

String str = "Hello, world!";
int index = str.lastIndexOf("o");
System.out.println(index); // 輸出8
  1. 使用contains()方法:該方法用于判斷字符串中是否包含指定的子字符串,返回true或false。

例如:

String str = "Hello, world!";
boolean contains = str.contains("world");
System.out.println(contains); // 輸出true
  1. 使用matches()方法:該方法用于判斷字符串是否匹配指定的正則表達式。

例如:

String str = "Hello, world!";
boolean isMatch = str.matches("Hello.*");
System.out.println(isMatch); // 輸出true
  1. 使用startsWith()和endsWith()方法:這兩個方法分別用于判斷字符串是否以指定的前綴開始或以指定的后綴結束,返回true或false。

例如:

String str = "Hello, world!";
boolean startsWith = str.startsWith("Hello");
boolean endsWith = str.endsWith("world!");
System.out.println(startsWith); // 輸出true
System.out.println(endsWith); // 輸出true

這些方法可以根據具體的需求選擇合適的方式進行字符串查找。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女