专注Java教育14年 全国咨询/投诉热线:444-1124-454
赢咖4LOGO图
始于2009,口口相传的Java黄埔军校
首页 学习攻略 Java学习 Java判断字符串是否包含字符的方法

Java判断字符串是否包含字符的方法

更新时间:2022-06-17 10:41:38 来源:赢咖4 浏览4761次

赢咖4小编来告诉大家Java判断字符串是否包含字符的方法:

1.包含方法

(1)说明

Contains() 方法当且仅当字符串包含指定的 char 值序列时才返回 true

(2)声明

public boolean contains(CharSequence s)

(3)返回值

如果字符串包含则返回真,否则返回假。

(4)实例

public static void main(String[] args) {
    String str = "abc";
    boolean status = str.contains("a");
    if(status){
      System.out.println ("included");
    }else{
      System.out.println ("not included");
    }
}

2.索引方法

(1)说明

indexof() 用于查找单词在字符串中的位置,判断字符串是否包含字符。

(2)声明

int indexOf(int ch,int fromIndex)

(3)返回值

indexof 的返回值为 int

(4)实例

public static void main(String[] args) {
    String str1 = "abcdefg";
    int result1 = str1.indexOf("a");
    if(result1 != -1){
      System. Out. Println ("string STR contains substring" a "+ result1);
    }else{
      System. Out. Println ("string STR does not contain substring" a "+ result1);
    }
}

以上就是Java判断字符串是否包含字符的方法细节。如果大家想了解更多相关知识,不妨来关注一下赢咖4的Java赢咖4在线学习,里面的课程内容从入门到精通,细致全面,很适合没有基础的小伙伴学习,希望对大家能够有所帮助哦。

提交申请后,顾问老师会电话与您沟通安排学习

免费课程推荐 >>
技术文档推荐 >>