Java String类方法

109 阅读2分钟

记录着自己遇到过,还记得记录的 String类方法

indexOf() 方法

  • public int indexOf(int ch): 返回指定字符在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1。

  • public int indexOf(int ch, int fromIndex): 返回从 fromIndex 位置开始查找指定字符在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1。

  • int indexOf(String str): 返回指定字符在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1。

  • int indexOf(String str, int fromIndex): 返回从 fromIndex 位置开始查找指定字符在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1。

    • ch -- 字符,Unicode 编码。
    • fromIndex -- 指定开始的下标位置
    • str -- 要搜索的子字符串。
public class Test {
    public static void main(String[] args) {

        String str = "aaa4565ac";
        // 查找字符串(str)中,5第一次出现的下标,存在则返回所在字符串下标;不在则返回-1.
        System.out.println(str.indexOf("5")); // 返回结果:4

        // 从下标为3的位置开始往后继续查找,包含当前位置(下标为3的位置)
        System.out.println(str.indexOf("a",3));// 返回结果:7

        //(与之前的差别:上面的参数是 String 类型,下面的参数是 int 类型)参考数据:a-97,b-98,c-99
        // 从头开始查找是否存在指定的字符
        System.out.println(str.indexOf(99));// 返回结果:8
        System.out.println(str.indexOf('c'));// 返回结果:8

        // 返回从指定的索引处开始向后搜索,开始查找指定字符在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1。
        System.out.println(str.indexOf(97,3));// 返回结果:7
        System.out.println(str.indexOf('a',3));// 返回结果:7

    }
}

substring() 方法

  • public String substring(int beginIndex): 根据传入的索引截取当前字符串,截取到末尾 (记得要用东西接它,它是有返回值的)

  • public String substring(int beginIndex, int endIndex): 根据传入开始和结束索引,截取字符串,并返回新的字符串 包括开始索引,不包括结束索引(包头,不包尾)

    • beginIndex -- 起始索引(包括), 索引从 0 开始。
    • endIndex -- 结束索引(不包括)。
public class StringTest {
    public static void main(String[] args) {
        String Str = new String("Hello World!!!");

        System.out.print("返回值 :" );
        System.out.println(Str.substring(4) );

        System.out.print("返回值 :" );
        System.out.println(Str.substring(4, 10) );
    }
}

image.png

toCharArray() 方法

  • 作用:toCharArray() 方法将字符串转换为字符数组

  • 示例

public class StringTest {
    public static void main(String[] args) {
        String str = "6a8s2s1f8gb";
        char[] chars = str.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            System.out.print(chars[i] + " ");
        }
    }
}

image.png

charAt() 方法

  • 作用: charAt() 方法用于返回指定索引处的字符。索引范围为从 0 到 length() - 1。
  • 参数:index -- 字符的索引。
  • 示例
public class StringTest {
    public static void main(String[] args) {
        String s = "hello world";
        char result = s.charAt(6);
        System.out.println( "输出第6位的字符: " +  result);
    }

image.png