Java字符串查找

本文介绍了Java中字符串查找的四种主要方法,包括按字符和字符串查找及其指定起始位置的变体。通过具体示例展示了每种方法的应用。

一、字符串查找的四种方式

  • int indexOf(int ch):根据字符的Unicode码查找;

  • int indexOf(String str):根据字符串查找;

  • int indexOf(int ch, int fromIndex):根据字符查找,但指定起始位置;

  • int indexOf(String str, int fromIndex)根据字符串查找,但指定起始位置。

public class Main_1 {
    public static void main(String[] args) {
        String s = "Test string";
        int n1 = s.indexOf('t');
        int n2 = s.indexOf("st");
        int n3 = s.indexOf("st", 4);
        System.out.println(n1);
        System.out.println(n2);
        System.out.println(n3);
    }
}

 

### Java 字符串查找方法 在 Java 中,`String` 类提供了多种内置的方法来支持字符串查找操作。以下是几种常见的实现方式及其特点: #### 使用 `indexOf()` 和 `lastIndexOf()` 这是最常用的字符串查找方法之一。通过调用这些函数,可以在目标字符串中定位子字符串或特定字符首次或最后一次出现的位置。 - **`indexOf(int ch)`**: 返回指定字符在此字符串中第一次出现处的索引。 - **`indexOf(String str)`**: 返回指定子字符串在此字符串中第一次出现处的索引。 - **`lastIndexOf(int ch)`**: 返回指定字符在此字符串中最右边出现处的索引[^3]。 示例代码如下: ```java public class IndexOfExample { public static void main(String[] args) { String str = "Hello world"; // 查找第一个 'o' 的位置 int firstOIndex = str.indexOf('o'); System.out.println("First occurrence of 'o': " + firstOIndex); // 查找最后一个 'l' 的位置 int lastLIndex = str.lastIndexOf('l'); System.out.println("Last occurrence of 'l': " + lastLIndex); } } ``` #### 遍历字符串并逐个比较字符 如果需要更灵活的方式或者要统计某个字符在整个字符串中的出现次数,则可以通过遍历来完成此任务。这种方法允许对每个字符执行自定义逻辑处理。 基于引用的内容提到一种具体做法就是利用循环配合条件判断来进行逐一匹配,并记录符合条件的结果数量以及它们各自所在的位置信息等细节数据[^4]。 下面是采用这种方式的一个例子程序片段: ```java public class CharCountInString { public static void main(String[] args){ String name="programmingisfunandchallenging"; char charToFind='i'; int count=0; int index=-1; while((index=name.indexOf(charToFind,index+1))!=-1){ count++; } System.out.printf("The character '%c' appears %d times.%n",charToFind,count); } } ``` 以上展示了如何在一个较长文本里寻找给定字母的所有实例数目。 #### 正则表达式模式匹配 (`Pattern`, `Matcher`) 对于复杂的查询需求来说,正则是非常强大的工具。它可以用来验证输入是否遵循某种格式、提取感兴趣的部分甚至替换不符合预期的内容等等。这里仅简单提及作为扩展知识点介绍[^2]。 例如检测邮箱地址有效性可写成这样一段脚本: ```java import java.util.regex.*; public class EmailValidator{ private Pattern pattern; private Matcher matcher; private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" +"[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; public EmailValidator(){ pattern = Pattern.compile(EMAIL_PATTERN); } /** * Validate hex with regular expression * * @param email email for validation * @return true valid email, false invalid email */ public boolean validate(final String email){ matcher = pattern.matcher(email); return matcher.matches(); } } ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

幼儿园大哥7

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

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

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

打赏作者

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

抵扣说明:

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

余额充值