c++ string类的常用方法_Java中String类的几种常用方法介绍

de7d7d9579fdb837cde1dd0ee1354224.png

1. length()

  • 返回值:int
  • 说明:返回指定字符串的长度
public static void main(String[] args) {String str = "This is a computer.";// 返回指定字符串的长度int length = str.length();System.out.println(length); // 19}

2. substring(int beginIndex, int endIndex)

  • 入参:beginIndex是开始索引的位置,endIndex结束索引的位置
  • 返回值:String
  • 说明:截取字符串,索引是从0开始,截取的字符串只截取到结束索引之前,以下程序中,beginIndex是2,对应i,endIndex是11,对应o,截取之后不是"is is a co",而是"is is a c",所以,使用这个方法时,要注意endIndex指向的位置
public static void main(String[] args) {String str = "This is a computer.";// 截取字符串String newStr = str.substring(2, 11);System.out.println(newStr); // is is a c }

3. charAt(int index):char

  • 入参:int
  • 返回值:char
  • 功能:指定索引,返回索引处的字符
public static void main(String[] args) {String str = "This is a dog.";// 返回指定索引处的charchar ch = str.charAt(3);System.out.println(ch); // s}

4. indexOf(String str)

  • 入参:String
  • 返回值:int
  • 说明:返回指定字符在该字符串中第一次出现的索引,在"This is a computer."中,有两个"is",indexOf(String str)方法可以获取某个字符串第一出现的位置
public static void main(String[] args) {String str = "This is a computer.";// 返回指定字符在该字符串中第一次出现的索引int index = str.indexOf("is");System.out.println(index); // 2}

5. isEmpty()

  • 返回值:boolean
  • 说明:验证字符串是否为空,使用这个方法是要注意,被验证的字符串必须是实例化对象,如果字符串是null,会抛出异常java.lang.NullPointerException。另外,多个空格同样不为空,比如str3就是多个空格组成的字符串,但不为空
public static void main(String[] args) {String str1 = "This is a computer.";String str2 = "";String str3 = " ";// 验证字符串是否为空boolean result1 = str1.isEmpty();boolean result2 = str2.isEmpty();boolean result3 = str3.isEmpty();System.out.println(result1); // falseSystem.out.println(result2); // trueSystem.out.println(result3); // false}

6. replaceAll(String regex, String replacement)

  • 入参:regex指定被替换的字符串,replacement指定替换的字符串
  • 返回值:String
  • 说明:替换字符串中指定的内容
public static void main(String[] args) {String str = "小明是一个学生";// 替换字符串中指定的内容String newStr = str.replaceAll("学生
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值