String类的常用方法

 时间:2026-02-13 05:22:00

1、获取字符串的长度 

方法:

public int length()

实例:

String str = new String("abcdefg");

int length = str.length();

String类的常用方法

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

方法:

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

public char charAt(int index)

实例:

String str = new String("abcdefg");

 char ch = str.charAt(3);

序号是从0 开始的,所以chatAt(3)是字符d

String类的常用方法

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

方法:

public int indexOf(String str)

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

public int indexOf(String str, intfromIndex)

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

public int lastIndexOf(String str)

实例:

String

str = new String("abcdefbg");

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

int lastIndex = str.lastIndexOf("b");

String类的常用方法

4、截取字符串的子串 

方法:

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

public String substring(int beginIndex)

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

public String substring(int beginIndex, int endIndex)

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

public boolean equalsIgnoreCase(String anotherString)

实例:

String str = new String("abcdefbg");

String str2 = str.substring(3);

String str3 = str.substring(3,5);

String类的常用方法

5、字符串比较

方法:

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

public int compareTo(String anotherString)

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

public int compareToIgnore(String anotherString)

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

public boolean equals(Object anotherObject)

String类的常用方法

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

方法:

转换成大写

public String toUpperCase()

转换成小写

public String toLowerCase()

实例:

String str1 = new String("bcdFg");

String str2 = str1.toLowerCase();

String str3 = str1.toUpperCase();

String类的常用方法

  • HHA蜂浆纸的使用方法
  • 网络安全团队如何构建
  • 一起来了解海洋动物“玳瑁”!
  • 象棋叠罗汉怎么玩
  • 男生派克服搭配什么裤子
  • 热门搜索
    关于环保的知识 知识经济时代 吊顶用什么材料好 来月经前有什么症状 如何运动减肥 初一地理知识点总结 骆驼奶的功效和作用 人参粉的功效与作用 薏仁的功效与作用 龟甲的功效与作用