字符串第一次出现的位置

前言

在Java编程中,经常会遇到查找字符串中某个子串第一次出现的位置的需求。本文将介绍几种常见的方法来实现这个功能,并给出相应的Java代码示例。

一、使用indexOf方法

Java中的String类提供了indexOf方法,可以查找子串在字符串中第一次出现的位置。该方法的定义如下:

public int indexOf(String str)

其中,str为要查找的子串,返回值为子串在字符串中第一次出现的位置,若未找到则返回-1。

下面是一个使用indexOf方法查找子串第一次出现位置的示例代码:

public class StringSearchDemo {
    public static void main(String[] args) {
        String str = "Hello, World!";
        String subStr = "World";
        int index = str.indexOf(subStr);
        if (index >= 0) {
            System.out.println("子串第一次出现的位置为:" + index);
        } else {
            System.out.println("未找到子串!");
        }
    }
}

上述代码中,字符串str中查找子串subStr的第一次出现位置,并输出结果。执行上述代码,输出结果为:

子串第一次出现的位置为:7

二、使用正则表达式

Java中的正则表达式也可以用来查找字符串中子串第一次出现的位置。可以使用Pattern类和Matcher类来实现。下面是使用正则表达式查找子串第一次出现位置的示例代码:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringSearchDemo {
    public static void main(String[] args) {
        String str = "Hello, World!";
        String subStr = "World";
        Pattern pattern = Pattern.compile(subStr);
        Matcher matcher = pattern.matcher(str);
        if (matcher.find()) {
            System.out.println("子串第一次出现的位置为:" + matcher.start());
        } else {
            System.out.println("未找到子串!");
        }
    }
}

上述代码中,使用Pattern类的compile方法将子串转换为正则表达式模式,然后使用Matcher类的find方法进行查找。若找到则输出子串第一次出现的位置,若未找到则输出未找到子串。

执行上述代码,输出结果为:

子串第一次出现的位置为:7

三、使用Apache Commons Lang库

Apache Commons Lang是一个提供常用的工具类的开源库,其中提供了StringUtils类,可以用来查找字符串中子串第一次出现的位置。下面是使用StringUtils类查找子串第一次出现位置的示例代码:

import org.apache.commons.lang3.StringUtils;

public class StringSearchDemo {
    public static void main(String[] args) {
        String str = "Hello, World!";
        String subStr = "World";
        int index = StringUtils.indexOf(str, subStr);
        if (index >= 0) {
            System.out.println("子串第一次出现的位置为:" + index);
        } else {
            System.out.println("未找到子串!");
        }
    }
}

上述代码中,使用StringUtils类的indexOf方法来查找子串第一次出现的位置。若找到则输出子串第一次出现的位置,若未找到则输出未找到子串。

执行上述代码,输出结果为:

子串第一次出现的位置为:7

总结

本文介绍了几种常见的方法来查找字符串中子串第一次出现的位置,包括使用String类的indexOf方法、使用正则表达式和使用Apache Commons Lang库。这些方法在实际编程中都是非常常用的,可以根据具体的需求来选择合适的方法。

类图

classDiagram
    class StringSearchDemo{
        +main(String[] args): void
    }
    class Pattern{
        -pattern: String
        +compile(String regex): Pattern
    }
    class Matcher{
        -pattern: Pattern
        -input: CharSequence
        +find(): boolean
        +start(): int
    }
    class StringUtils{
        +indexOf(CharSequence seq, CharSequence searchSeq): int
    }
    class String{
        +indexOf(String str): int
    }
    StringSearchDemo --> Pattern
    Pattern *-- Matcher
    StringUtils <-- StringSearchDemo
    String