要检查字符串B中是否包含特定字符串A,我们可以使用该方法
string.Contains()具有以下语法:
b.contains(a); //如果a包含在b中,则返回true,否则返回false
String.Contains()方法可用于验证字符串中是否可以找到字符序列。
该方法以区分大小写的方式查找字符串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.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()方法返回另一个字符串中的char或者字符串的第一个索引。
如果找不到该方法返回-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
日期:2020-06-02 22:15:21 来源:oir作者:oir