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

Java函数库中的字符串搜索和替换函数使用方法

发布时间:2023-12-04 08:57:48

在Java的函数库中,有很多用于字符串搜索和替换的函数可以使用。下面将介绍其中几个常用的函数及其使用方法。

1. indexOf()函数:

   这个函数用于搜索字符串中的指定字符或子字符串,并返回其在字符串中的索引位置。如果没有找到,则返回-1。

   例如:String str = "Hello World";

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

         System.out.println(index);  // 输出为4

2. lastIndexOf()函数:

   这个函数与indexOf()函数类似,不过它从末尾开始搜索字符串,返回最后一个匹配字符或子字符串的索引位置。

   例如:String str = "Hello World";

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

         System.out.println(index);  // 输出为7

3. contains()函数:

   这个函数用于检查字符串中是否包含指定的字符或子字符串。如果包含,则返回true;否则,返回false。

   例如:String str = "Hello World";

         boolean contains = str.contains("World");

         System.out.println(contains);  // 输出为true

4. startsWith()和endsWith()函数:

   这两个函数用于检查字符串是否以指定的字符或子字符串开始或结束。如果是,则返回true;否则,返回false。

   例如:String str = "Hello World";

         boolean startsWith = str.startsWith("Hello");

         boolean endsWith = str.endsWith("World");

         System.out.println(startsWith);  // 输出为true

         System.out.println(endsWith);  // 输出为true

5. replace()函数:

   这个函数用于将字符串中的指定字符或子字符串替换为新的字符或子字符串。

   例如:String str = "Hello World";

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

         System.out.println(newStr);  // 输出为"Hello Java"

以上是一些常用的字符串搜索和替换函数的使用方法。在实际编程中,可以根据具体需求选择使用适当的函数来完成字符串操作。