Java:判断一个字符串中是否存在另一个字符子串以及判断一个字符串中是否存在指定字符

这篇博客介绍了如何在Java中使用`contains`方法判断字符串是否包含另一个字符子串,以及如何利用`indexOf`方法检查字符串中是否存在指定字符。示例代码清晰展示了这两种判断方法的用法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 for
Returns:
	true if this string contains s, false otherwise
Throws:
	NullPointerException - if s is null
Since:
	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) == ch
 
is true. For other values of ch, it is the smallest value k such that:
 this.codePointAt(k) == ch
 
is 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.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值