Java 判断字符串是否存在 - contains() 和 indexOf() 方法
可以使用 Java 中的 contains() 函数来判断一个字符串是否存在于另一个字符串中。下面是一个示例代码:
String str1 = 'Hello World';
String str2 = 'World';
if(str1.contains(str2)){
System.out.println('字符串存在');
} else {
System.out.println('字符串不存在');
}
输出结果为:字符串存在
另外,还可以使用 indexOf() 函数来查找字符串,并返回所在位置的索引值。如果返回-1,则表示字符串不存在。示例代码如下:
String str1 = 'Hello World';
String str2 = 'World';
int index = str1.indexOf(str2);
if(index != -1){
System.out.println('字符串存在,位置为:' + index);
} else {
System.out.println('字符串不存在');
}
输出结果为:字符串存在,位置为:6
原文地址: https://www.cveoy.top/t/topic/nGEs 著作权归作者所有。请勿转载和采集!