java中怎么判断一个字符串中包含某个字符或字符串

如题所述

Java中字符串中子串的查找共有四种方法,如下:

1、int indexOf(String str) :返回第一次出现的指定子字符串在此字符串中的索引。 

2、int indexOf(String str, int startIndex):从指定的索引处开始,返回第一次出现的指定子字符串在此字符串中的索引。 

3、int lastIndexOf(String str) :返回在此字符串中最右边出现的指定子字符串的索引。 

4、int lastIndexOf(String str, int startIndex) :从指定的索引处开始向后搜索,返回在此字符串中最后一次出现的指定子字符串的索引。

示例 

下面的示例说明了 indexOf 方法的用法。

12345678910111213141516171819function IndexDemo(str2){ var str1 = "BABEBIBOBUBABEBIBOBU" var s = str1.indexOf(str2); return(s); }public class FirstDemo {   /**     *API中String的常用方法     */   // 查找指定字符串是否存在   public static void main(String[] args) {     String str1 = "abcdefghijklmnabc";     // 从头开始查找是否存在指定的字符     System.out.println(str1.indexOf("c"));     // 从第四个字符位置开始往后继续查找     System.out.println(str1.indexOf("c", 3));     //若指定字符串中没有该字符则系统返回-1     System.out.println(str1.indexOf("x")); 

温馨提示:答案为网友推荐,仅供参考
相似回答