String字符串中常用的方法(一)

131 阅读2分钟

前言

字符串String时我们常用的一种类型,预期相关的有很多方法使我们可以更好的使用和处理字符串,让我们一起了解一下吧。


提示:以下是本篇文章正文内容,下面案例可供参考

一、 indexOf()方法

indexOf()方法有两种:

  • indexOf(String str):返回指定子字符串在此字符串中第一次出现处的索引。

1.png

 public class Demo {
     public static void main(String[] args) {
 ​
         String str_1 = "学习使我快乐";
         String str_2 = "xuexishiwokuaile";
 ​
         int index_1= str_1.indexOf("使");
         int index_2 = str_2.indexOf("i");
 ​
         System.out.println(index_1);
         System.out.println(index_2);
     }
 }

其中 String str为要指定的字符,该方法最后返回值为 int,是寻找到后的索引。

3.png

indexOf(String str , int fromIndex):返回指定子字符串在此字符串中第一次出现处的索引,从指定的索引开始。

2.png

         int index_3 = str_2.indexOf("i" , 6);
         System.out.println(index_3);

其中 String str 为要指定查找的子字符串,而 int fromIndex是指定要从那个索引开始寻找。

4.png 如果 指定字符没有出现 则返回 -1

二、lastIndexOf() 方法

返回指定子字符串在此字符串中最后一次出现处的索引,从指定的索引开始反向搜索。

5.png

如果 指定字符没有出现 则返回 -1

         int index_5 = str_2.lastIndexOf("u" , 6);
         System.out.println(index_5);

其中 String str 为要指定查找的子字符串,而 int fromIndex是指定要从那个索引开始 反向 寻找。

6.png

三、lastIndexOf() 方法

当且仅当此字符串包含指定的 char 值序列时,返回 true。

7.png

         boolean index_6 = str_2.contains("kuaile");
         System.out.println(index_6);
         boolean index_7 = str_2.contains("bu");
         System.out.println(index_7);

判断字符串中是否包含某个指定的字符(或子串)。

8.png

四、charAt() 方法

返回指定索引处的 char 值。索引范围为从 0length() - 1。序列的第一个 char 值位于索引 0 处,第二个位于索引 1 处,依此类推,这类似于数组索引。

9.png 其中返回值为 char类型 的。

         char index_8 = str_1.charAt(2);
         char index_9 = str_2.charAt(5);
         System.out.println(index_8);
         System.out.println(index_9);

10.png

五、substring() 方法

substring() 方法有两种形式:

  • substring(int beginIndex):返回一个新的字符串,它是此字符串的一个子字符串。该子字符串从指定索引处的字符开始,直到此字符串末尾。
        String index_10 = str_1.substring(4);

        System.out.println(index_10);

11.png

  • substring(int beginIndex ,int endIndex):返回一个新字符串,它是此字符串的一个子字符串。该子字符串从指定的 beginIndex 处开始,直到索引 endIndex - 1 处的字符。因此,该子字符串的长度为 endIndex-beginIndex
         String index_11 = str_2.substring( 2 , 6);
 ​
         System.out.println(index_11);

12.png 注:并不是将原字符串进行修改,而是将指定范围内的元素生成一个新的字符串返回过来。

六、startsWith()/endsWith()方法

判断字符串是否是指定字符为 前/后缀

13.png

        boolean index_12 = str_3.startsWith("www");

        System.out.println(index_12);

14.png

        boolean index_14 = str_3.startsWith("com");
        System.out.println(index_14);

15.png 其中返回值问Boolean类型,判断是否存在指定前缀。

         boolean index_13 = str_3.endsWith("com");
         
         System.out.println(index_13);

16.png

         boolean index_15 = str_3.endsWith("kaifamiao");
         System.out.println(index_15);

17.png