这篇文章将为大家详细讲解有关java判断字符串是否包含指定字符的方法,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

一、contains方法

1:描述

java.lang.String.contains() 方法返回true,当且仅当此字符串包含指定的char值序列。

2:声明

public boolean contains(CharSequence s)

3:返回值

此方法返回true,如果此字符串包含,否则返回false。

4:实例

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

二、indexOf方法

1:描述

java.lang.String.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("字符串str中包含子串“a”"+result1); }else{ System.out.println("字符串str中不包含子串“a”"+result1); } }

关于java判断字符串是否包含指定字符的方法就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。