Java在另一个字符串中查找字符串

示例

要检查一个特定的字符串是否a被包含在一个字符串b或没有,我们可以使用该方法的语法如下:String.contains()

b.contains(a); // 如果b中包含a,则返回true,否则返回false

该方法可用于验证是否可以在字符串中找到a 。该方法以区分大小写的方式在字符串中查找字符串。String.contains()CharSequenceab

String str1 = "Hello World";
String str2 = "Hello";
String str3 = "helLO";

System.out.println(str1.contains(str2)); //打印真实
System.out.println(str1.contains(str3)); //打印错误

Ideone现场演示


要找到一个字符串在另一个字符串中开始的确切位置,请使用:String.indexOf()

String s = "this is a long sentence";
int i = s.indexOf('i');    // 字符串中的第一个“ i”位于索引2
int j = s.indexOf("long"); // the index of the first occurrence of "long" in s is 10
int k = s.indexOf('z');    // k为-1,因为在String s中找不到“ z”
int h = s.indexOf("LoNg"); // h is -1 because "LoNg" was not found in String s

Ideone现场演示

该方法返回a或in another的第一个索引。如果找不到该方法,则返回该方法。String.indexOf()charStringString-1

注意:该方法区分大小写。String.indexOf()

忽略大小写的搜索示例:

String str1 = "Hello World";
String str2 = "wOr";
str1.indexOf(str2);                               // -1
str1.toLowerCase().contains(str2.toLowerCase());  // 真正
str1.toLowerCase().indexOf(str2.toLowerCase());   // 6

Ideone现场演示