欢迎访问宙启技术站
智能推送

Java函数实现字符串的搜索和替换

发布时间:2023-05-22 12:58:31

在Java中,字符串是一个非常常见的数据类型,我们经常需要对字符串进行搜索和替换的操作。Java提供了一些字符串处理函数,可以方便地完成这些操作。

一、字符串搜索函数

1、indexOf()

indexOf()函数可以在字符串中搜索指定字符串的位置,返回该字符串的索引值,如果未找到则返回-1。

例如:

    String str = "hello world";

    int index = str.indexOf("world");

    System.out.println(index);

输出结果为:6

2、lastIndexOf()

lastIndexOf()函数可以在字符串中从后往前搜索指定的字符串,返回该字符串最后出现的位置,如果未找到则返回-1。

例如:

    String str = "hello world";

    int index = str.lastIndexOf("o");

    System.out.println(index);

输出结果为:7

3、startsWith()

startsWith()函数可以判断字符串是否以指定的字符串开头,返回一个布尔值。

例如:

    String str = "hello world";

    boolean start = str.startsWith("hello");

    System.out.println(start);

输出结果为:true

4、endsWith()

endsWith()函数可以判断字符串是否以指定的字符串结尾,返回一个布尔值。

例如:

    String str = "hello world";

    boolean end = str.endsWith("world");

    System.out.println(end);

输出结果为:true

5、contains()

contains()函数可以判断字符串是否包含指定的字符串,返回一个布尔值。

例如:

    String str = "hello world";

    boolean contain = str.contains("llo");

    System.out.println(contain);

输出结果为:true

二、字符串替换函数

1、replace()

replace()函数可以将字符串中指定的字符或字符串替换成新的字符或字符串。

例如:

    String str = "hello world";

    String newStr = str.replace("world", "Java");

    System.out.println(newStr);

输出结果为:hello Java

2、replaceAll()

replaceAll()函数可以使用正则表达式将字符串中匹配的内容替换成新的内容。

例如:

    String str = "hello world";

    String newStr = str.replaceAll("\\b\\w{5}\\b", "Java");

    System.out.println(newStr);

输出结果为:Java Java

在上面的示例中,我们使用正则表达式将字符串中所有长度为5的单词替换为“Java”。

3、replaceFirst()

replaceFirst()函数与replaceAll()函数类似,但只会替换 个匹配项。

例如:

    String str = "hello world";

    String newStr = str.replaceFirst("\\b\\w{5}\\b", "Java");

    System.out.println(newStr);

输出结果为:Java world

总结

在Java中,字符串的搜索和替换是非常常见的操作,我们可以借助Java提供的字符串处理函数轻松地完成这些操作。在实际编程中,我们可以根据实际需要选择合适的函数来完成相应的操作,以提高效率和可读性。