Java:判断一个字符串中包含指定字符子串,判断一个字符串中存在指定字符
字符串的contains方法可以判断一个字符串中是否存在另一个字符子串,示例如下
String Str = "Hello , World .";if (Str.contains("Hello")) {System.out.println("Str contains Hello");}
函数说明:
public boolean contains(CharSequence s)Returns true if and only if this string contains the specified sequence of char values.Parameters:s - the sequence to search forReturns:true if this string contains s, false otherwiseThrows:NullPointerException - if s is nullSince:1.5
注意:contains方法的参数要求是实现了CharSequence 接口的类,包括CharBuffer, Segment, String, StringBuffer, StringBuilder,不包括字符
如果你想对单个字符用contains方法,可以这样使用
String Str = "Hello , World .";if (Str.contains(""+'H')) {System.out.println("Str contains H");}
使用indexOf判断字符串是否中存在指定字符,实现样例如下:
String Str = "Hello , World .";if (Str.indexOf('H')!=-1) {System.out.println("Str contains H");}//indexOf返回的是字符在字符串中的位置,如果不存在则返回-1
函数说明:
public int indexOf(int ch)Returns the index within this string of the first occurrence of the specified character. If a character with value ch occurs in the character sequence represented by this String object, then the index (in Unicode code units) of the first such occurrence is returned. For values of ch in the range from 0 to 0xFFFF (inclusive), this is the smallest value k such that:this.charAt(k) == chis true. For other values of ch, it is the smallest value k such that:this.codePointAt(k) == chis true. In either case, if no such character occurs in this string, then -1 is returned.Parameters:ch - a character (Unicode code point).Returns:the index of the first occurrence of the character in the character sequence represented by this object, or -1 if the character does not occur.
如果觉得《Java:判断一个字符串中是否存在另一个字符子串以及判断一个字符串中是否存在指定字符》对你有帮助,请点赞、收藏,并留下你的观点哦!