zoukankan      html  css  js  c++  java
  • 字符串截取

    方法一:通过split()

    此方法返回的是一个字符串数组类型。

    1.只传一个参数:split(String regex)

    将正则传入split(),根据给定正则表达式的匹配拆分此字符串。不过通过这种方式截取会有很大的性能损耗,因为分析正则非常耗时。

    public class day1011 {
        public static void main(String[]args){
            String str="hsybcyusdgyg@163.com";
            String[] str1=str.split("y");
            for(int i=0;i<str1.length;i++){
                System.out.println(str1[i].toString());
            }
        }
    }

    运行结果:

    hs

    bc

    usdg

    g@163.com

    2.传入两个参数:split(String regex,int limit)

    regex -- 正则表达式分隔符。

    limit -- 分割的份数。

    将正则和份数传入split()。根据给定正则表达式的匹配和想要分割的份数来拆分此字符串。

    public class day1011 {
        public static void main(String[]args){
            String str="hsybcyusdgyg@163@com";
            String[] str1=str.split("@",2);
            for(int i=0;i<str1.length;i++){
                System.out.println(str1[i].toString());
            }
        }
    }

    运行结果:

    hsybcyusdgyg

    163@com

    方法二:通过subString()方法来进行字符串截取

    1、只传一个参数:subString(int beginIndex)

    将字符串从索引号为beginIndex开始截取,一直到字符串末尾。(注意索引值从0开始);

    public class day1011 {
        public static void main(String[]args){
            String str="hsybcyusdgyg@163@com";
            String st2=str.substring(5);
            System.out.println(st2);
        }
    }

    运行结果:

    yusdgyg@163@com

    2、传入两个参数:substring(int beginIndex, int endIndex)

    从索引号beginIndex开始到索引号endIndex结束(返回结果包含索引为beginIndex的字符不包含索引endIndex的字符),如下所示:

    public class day1011 {
        public static void main(String[]args){
            String str="hsybcyusdgyg@163@com";
            String st2=str.substring(2,7);
            System.out.println(st2);
        }

    运行结果:

    ybcyu

    3、根据某个字符截取字符串

    这里根据”@”截取字符串(也可以是其他子字符串)

    public class day1011 {
        public static void main(String[]args){
            String str="hsybcyusdgyg@163@com";
            String st2=str.substring(2,str.indexOf("@"));
            System.out.println(st2);
        }
    }

    运行结果:

    ybcyusdgyg

     

    欢迎大家批评指正,指出问题,谢谢!

  • 相关阅读:
    15天玩转redis —— 第四篇 哈希对象类型
    15天玩转redis —— 第三篇 无敌的列表类型
    15天玩转redis —— 第二篇 基础的字符串类型
    15天玩转redis —— 第一篇 开始入手
    双十一来了,别让你的mongodb宕机了
    AutoIncrement无法设置的问题
    Frame animation
    Tween animation
    在project窗口中快速定位文件
    Activty左出右进动画
  • 原文地址:https://www.cnblogs.com/yhcTACK/p/15395324.html
Copyright © 2011-2022 走看看