在另一个字符串中查找字符串
要检查特定字符串 a 是否包含在字符串 b 中,我们可以使用 String.contains() 方法,语法如下:
b.contains(a); // Return true if a is contained in b, false otherwise
该 String.contains() 方法可用于验证一个 CharSequence 可以在字符串中找到。该方法以区分大小写的方式查找字符串 b 中的字符串 a。
String str1 = "Hello World";
String str2 = "Hello";
String str3 = "helLO";
System.out.println(str1.contains(str2)); //prints true
System.out.println(str1.contains(str3)); //prints false
要找到 String 在另一个 String 中开始的确切位置,请使用 String.indexOf() :
String s = "this is a long sentence";
int i = s.indexOf('i'); // the first 'i' in String is at index 2
int j = s.indexOf("long"); // the index of the first occurrence of "long" in s is 10
int k = s.indexOf('z'); // k is -1 because 'z' was not found in String s
int h = s.indexOf("LoNg"); // h is -1 because "LoNg" was not found in String s
该 String.indexOf() 方法返回在另一个 String 一个 char 或 String 的第一索引。如果找不到,则该方法返回 -1。
注意 : String.indexOf() 方法区分大小写。
忽略案例的搜索示例:
String str1 = "Hello World";
String str2 = "wOr";
str1.indexOf(str2); // -1
str1.toLowerCase().contains(str2.toLowerCase()); // true
str1.toLowerCase().indexOf(str2.toLowerCase()); // 6