• java中分割字符串总结 - 超级无敌详细版本。不仅要熟悉各种方法还要做到灵活运用。


    目录

    1.split()

    2.indexof()

    3.lastIndexOf()

    4.substing() 

    小技巧


    1.split()

     可有两个参数

    只有第一个参数,就是以这个符号来分割

    例如:

    String str="a,b,c";

    String[] split=str.split(",");

    则 split[0]=a split[1]=b  split[2]=c

    两个参数都有的时候,第一个为用来分割的符号,第二个为分割后的数组长度(如果设置的长度大于分割后的长度则以分割的长度为准)。

    设置的长度大于分割后的长度            如:

    String str  = "s,ssc,add";
    System.out.println(str.split(",", 5).length);

    输出结果为 3 

    设置的长度小于于分割后的长度

    String str  = "s,ssc,add";
    for (String s1 : str.split(",", 2)) {
        System.out.println(s1);
    }

    输出结果为

    s

    ssc,add

    2.indexof()

     indexof可有两个参数,返回值是一个索引值。

    只有第一个参数,可以为单个字符或者字符串(String)

    如:

    String str  = "sscaddss";
    int c1 = str.indexOf("s");
    System.out.println(c1);

    输出为 0 (为第一个s的索引值)

    int c2 = str .indexOf("ss");

    System.out.println(c2);

    输出为 0

    有两个参数,第二个参数代表从哪个索引开始查找。

    String str = "sscaddss";
    int c = str.indexOf("s",1); 代表从索引1开始查找,返回第一个s在整个字符串str里面的索引值
    System.out.println(c);

    输出为 1      

    indexof(int ch)这个用法是indexof里面稍微难理解一点的用法。

    先copy一段文字

    String 类中的indexof(int ch)方法的形参列表为什么采用int型而不采用char型?
    涉及到了增补字符,因为char型只有65536个字符,不能表示完所有的字符还有一些诸如"火星文"的未知字符,因此用char型来表示是完全不够的,而int类型的范围是- 2 ^ 31 ~2 ^ 31 - 1,足够用来表示已知和未知的字符,并且int跟char海涉及到隐式字符转换,这样用int作为形参不仅没有多费功夫还扩大了indexof的涵盖范围。
    ————————————————
    版权声明:本文为CSDN博主「java小马达」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
    原文链接:https://blog.csdn.net/m0_49022755/article/details/111451875

    indexof(int ch)这里传入的int是一个ASCII码,ASCII码转为字符后再去查找,返回也是索引

    如:

    String str = "sscaddss";
    int c = str.indexOf(115);  s的ASCII码为115 和 str.indexOf("s")一样
    System.out.println(c);

    输出为 0

    3.lastIndexOf()

    用法、参数的意思和indexOf()一样,只是lastIndexOf()是从后往前,最后一个字符的索引为0。

    4.substing() 

    substring(int beginIndex) :  返回从beginIndex开始后面所有的字符

    如:

    String str = "sscaddss";
    String substring = str.substring(3);
    System.out.println(substring);

    输出 addss

    substring(int beginIndex,int endIndex) : 返回在beginIndex和endIndex之间的字符,包括beginIndex不包括endIndex

    String str = "sscaddss";
    String substring = str.substring(3,7);
    System.out.println(substring);

    输出为adds

    小技巧

    如果要在字符串中取出特定一部分,可以结合indexof和substring。

    如:取出[ student:{"name":"pjy","score":88}]中的 "score" : 88

    String str = "[ student:{\"name\":\"pjy\",\"score\":88}]";
    String substring = str.substring(str.indexOf("\"score\""), str.indexOf("88")+2);
    //为啥+2可阅读本文第四点。
    System.out.println(substring);

     

     

  • 相关阅读:
    快速重拾 Tmux
    Spring整合Junit单元测试
    常用sql语句
    【AIGC核心技术剖析】扩大富有表现力的人体姿势和形状估计SMPLer-X模型
    第六章《凸优化核心过程:真正搞懂梯度下降过程》
    C++基础语法详解
    关于边缘联邦学习的研究方向以及现状综述阅读笔记
    信息与编码(补码的作用)
    神经网络-最大池化的使用
    【golang】pprof性能调优工具的具体使用(带案例)
  • 原文地址:https://blog.csdn.net/qq_61672548/article/details/125535675