zoukankan      html  css  js  c++  java
  • java中根据不同需求切割字符串

    public class Demo0722 {
        public static void main(String[] args) {
            
              String a = "测试一下怎么截取字符串123450,随便输UYGqwer09874UUBi0jsad这样就可以吗???"; 
              String reg ="[u4e00-u9fa5]"; 
              Pattern pat = Pattern.compile(reg); 
              Matcher mat=pat.matcher(a); 
              String repickStr = mat.replaceAll("");
              System.out.println("去除汉字后:"+repickStr);
              System.out.println("去除汉字后为====="+a.replaceAll("[u4e00-u9fa5]", ""));
              System.out.println("拿到的数字为====="+a.replaceAll("[^0-9]",""));
              System.out.println("");
              
              String regex = "[^u4e00-u9fa5]";
              Pattern pattern = Pattern.compile(regex);
              Matcher matcher = pattern.matcher(a); 
              String result = matcher.replaceAll("");
              System.out.println("只要汉字:"+result);
              System.out.println("拿到的汉字是====="+a.replaceAll("[^u4e00-u9fa5]", ""));
              System.out.println("");
             
              String result1 = a.substring(a.indexOf("截取")+1,a.indexOf("可以"));//根据关键字截取一段字符串 
              System.out.println("想要的字符串为-------"+result1);
              String result2 = a.split(",")[0];//根据指定关键字分割两部分,取后半部分则使用[1]
              System.out.println("想要的字符串部分为------"+result2);
              String result3 = a.substring(4, 10);//根据index来截取字符串
              System.out.println("想要的字符串为-------"+result3);
              String result4 = a.split("0")[1];//截取两个0之间的字符串
              System.out.println("相同字符之间的字符为------"+result4);
              String result5 =a.substring(0,a.lastIndexOf("0"));//根据字符0最后一次出现来截取
              System.out.println("结果为----"+result5);
        }
    }

            截取字符串代码如上,控制台输出结果如下图

           

           正常来说截取字符串用到最多的几个方法就是split跟substring。split方法一般是将字符串截取成两部分,返回一个数组类型,一般我们需要的大多是String类型的,所以在后面加下[0]或者[1]。但是当字符串中出现两个以上的相同字符时,这时候如果我们以这个重复的字符为关键字来截取的话,那么截取得到的就是以这个字符分割的几个部分。举例:截取字符串为“12304560789”,这时候以0截取,那么我们得到的结果为[123, 456, 789],想要拿到第几个0之间的字符串在后面加上index下标即可。

           截取字符串中的空格:第一种是首尾有空格,这时候使用String中的trim()方法,但是我以前遇到过处理excel表格中的空格问题,使用这个方法就不行了。后来百度了一下发现是因为ASCII码的问题,在java中空格是32,但在excel中空格是160,所以我们想在excel里面用这个方法去除空格的话就不行了。第二种是字符串中间有空格,这时候使用replace()方法,即replace(" ",""),这里要注意,前面那个双引号中间是有一个空格的长度。

  • 相关阅读:
    SpringBoot之集成Socket
    SpringBoot之集成WebSocket
    SpringBoot之统一异常处理
    请求的转发和重定向
    5+App使用定位
    将Tomcat注册为Windows服务
    Tomcat环境变量设置
    CentOS7搭建Gitlab详细过程
    Python 12 内置函数
    Python 11 生成器
  • 原文地址:https://www.cnblogs.com/shitechnology/p/13361900.html
Copyright © 2011-2022 走看看