Java中String类的一些方法

    技术2026-02-17  14

    在做实验的过程中经常会用到String类的一些方法,这篇博客将常用的String类方法做一个总结。 1.获取字符串的长度

    方法:

    public int length()

    2.获取字符串某一位置字符

    方法:

    返回字符串中指定位置的字符;

    public char charAt(int index)

    3.查找子串在字符串中的位置

    方法:

    public int indexOf(String str)

    用于查找当前字符串中字符或子串,子串在当前字符串中从左边起首次出现的位置,若没有出现则返回-1。

    public int indexOf(String str, intfromIndex)

    方法与第一种类似,区别在于该方法从fromIndex位置向后查找。

    public int lastIndexOf(String str)

    4.截取字符串的子串

    方法:

    从beginIndex位置起,从当前字符串中取出剩余的字符作为一个新的字符串返回

    public String substring(int beginIndex)

    该方法从beginIndex位置起,从当前字符串中取出到endIndex-1位置的字符作为一个新的字符串返回。

    public String substring(int beginIndex, int endIndex)

    相似equals方法,但忽略大小写。

    public boolean equalsIgnoreCase(String anotherString)

    5.字符串比较

    方法:

    该方法是对字符串内容按字典顺序进行大小比较,通过返回的整数值指明当前字符串与参数字符串的大小关系。若当前对象比参数大则返回正整数,反之返回负整数,相等返回0。

    public int compareTo(String anotherString)

    与compareTo方法相似,但忽略大小写。

    public int compareToIgnore(String anotherString)

    比较当前字符串和参数字符串,在两个字符串相等的时候返回true,否则返回false。

    public boolean equals(Object anotherObject)

    6.对字符串中的字符进行大小写转换

    方法:

    转换成大写

    public String toUpperCase()

    转换成小写

    public String toLowerCase()

    Processed: 0.011, SQL: 9