字符串:获取,截取,转换,分割四种方法

String 中与获取字符串常用的方法有

  1. public int length() 获取字符串的长度。
String a ="sdklc mdfas";
        System.out.println("字符串的长度为:"+a.length());
  1. public String concat(String str) 将当前字符串和参数字符串拼接为一个新的字符串。(由于String具有不可更改性,所以想要两个字符串在一起时可以用concat)
 String str = "我是世界上";
        String str2 = "最可爱的人";
        String str3 =str.concat(str2);
        System.out.println(str3);
  1. public char charAt( int a ) 获取指定索引位置的单个字符。
String str4 = "adasdasdvsc";
        System.out.println("在第5号索引位置的字母是"+str4.charAt(5));

4.public int indeof(String str) 查找参数字符串在本字符串中第一次出现的索引位置,如果没有返回 -1值。

String original = "ABCDeFGeeeee";
        System.out.println("e在字符串中第一次出现的索引位置是:"+original.indexOf("e"));

字符串从大的字符串截取小的字符串的方法:

两种重载方式:

  1. public String substring(int index) index是索引的意思,获取从参数索引位置的字符到最后。
  2. public String substring(int index, int index),获取从左参数索引位置到右参数索引位置前一个,即左闭右开。
String str = "helloword";
        //现在我只想要word
        //1.用indexof(想要找的东西)
        String str2 = str.substring(str.indexOf("w"));
        //2.直接输入索引位置
        String str3 = str.substring(5);
        //3.[左索引位置,右索引位置)不包含右边索引
        String str4 = str.substring(5,9);
        System.out.println(str4);

ps:双引号下的字符串是不可以改变的

String a ="abc" ;
        System.out.println(System.identityHashCode(a));
         a ="cba";
        System.out.println(System.identityHashCode(a));

内容未改变但是地址值发生了改变。

字符串转换的方法

  1. public char[ ] toCharArray() 转换成字符数组。
  2. public byte[ ] getBytes(); 转换成一个字节数组。
  3. public String replace(Charsequence oldString,Charsequence newString) 将字符串中原有的转换为新的放在一个新字符串中。
String oldString ="你大爷的";
        String newString = oldString.replace("大爷", "**");
        System.out.println(newString);

字符串的分割方法:
1.public String[ ] Spolit(String regex) 里面是一个正则表达式,遇到 英文中的点 “.”时 注意加前面加//

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值