判断字符在字符串中出现与否的四种方法

判断字符在字符串中出现与否的四种方法

在 Java 中,判断一个字符是否在字符串中出现有多种方法。以下是几种常见的方法:

方法一:使用 String.indexOf(char ch)

indexOf 方法返回指定字符在字符串中第一次出现的索引,如果字符不存在则返回 -1。

    public static void main(String[] args) {
        String str = "!@#$%^&*()-+";
        char ch = '@';

        if (str.indexOf(ch) != -1) {
            System.out.println(ch + " 在字符串中出现");
        } else {
            System.out.println(ch + " 不在字符串中出现");
        }
    }

方法二:使用 String.contains(CharSequence s)

contains 方法用于判断字符串是否包含指定的字符序列。需要注意的是,contains 方法接受 CharSequence 参数,因此需要将字符转换为字符串。

    public static void main(String[] args) {
        String str = "!@#$%^&*()-+";
        char ch = '@';

        if (str.contains(String.valueOf(ch))) {
            System.out.println(ch + " 在字符串中出现");
        } else {
            System.out.println(ch + " 不在字符串中出现");
        }
    }

方法三:使用正则表达式 String.matches(String regex)

matches 方法用于判断字符串是否匹配给定的正则表达式。你可以构造一个正则表达式来检查字符是否在字符串中。

    public static void main(String[] args) {
        String str = "!@#$%^&*()-+";
        char ch = '@';

        if (str.matches(".*" + Pattern.quote(String.valueOf(ch)) + ".*")) {
            System.out.println(ch + " 在字符串中出现");
        } else {
            System.out.println(ch + " 不在字符串中出现");
        }
    }

方法四:使用 StringBuilder 或 StringBuffer

虽然这种方法不太常用,但也可以通过构建一个包含所有特殊字符的字符串来检查。

    public static void main(String[] args) {
        String str = "!@#$%^&*()-+";
        char ch = '@';

        StringBuilder sb = new StringBuilder(str);
        if (sb.indexOf(String.valueOf(ch)) != -1) {
            System.out.println(ch + " 在字符串中出现");
        } else {
            System.out.println(ch + " 不在字符串中出现");
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

王小二_Leon

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值