【问题标题】:After we split a String via RegEx, how could we get the length of new String?通过正则表达式拆分字符串后,我们如何获得新字符串的长度?
【发布时间】:2016-03-31 09:29:16
【问题描述】:
public class TestString {
public static void main(String[] args) {
    String str = "AaaaABBBBcc&^%adfsfdCCOOkk99876 _haHA";
    String[] upStr = str.split("[a-z0-9&^% _]");
    System.out.println("Printout uppercase");

    for (String outUp : upStr){
        System.out.print(outUp);
    }
    System.out.println("\n" + upStr.length);

“长度”是错误的,那么,值从何而来? 我们怎样才能得到真正的长度?

    System.out.println("\n Printout lowercase");
    String[] lowStr = str.split("[A-Z0-9&^% _]");
    for (String outLow : lowStr){
        System.out.print(outLow);
    }
    System.out.println("\n" + lowStr.length);

    System.out.println("\n non-English");
    String[] nonEng = str.split("[A-Za-z]");
    for (String outNonEng : nonEng){
        System.out.print(outNonEng);
    }
    System.out.println("\n" + nonEng.length);

所以我的问题是:

  1. length的值不对,is是哪里来的?
  2. 我怎样才能得到正确的String[] 长度?

【问题讨论】:

  • 长度似乎正确
  • 我建议您阅读:- stackoverflow.com/a/22259885/1996394
  • 打印输出大写AABBBBCCOOHA其实当前长度是12;打印输出小写 aaaccadfsfdkkha 非英语 &^%99876 _
  • length 在这种情况下是数组中的项目数。你怎么会说“新字符串的长度”?
  • 不要拆分,使用replaceAll("[^A-Z]+", "").length查看大写字母数量,使用replaceAll("[^a-z]+", "").length查看小写字母数量。

标签: regex string split


【解决方案1】:

您可能希望这样做:

public static void main(String[] args) {
        String str = "AaaaABBBBcc&^%adfsfdCCOOkk99876 _haHA";
        String[] upStr = str.replaceAll("[^A-Z]", "").split("(?!^)");
        String[] lowStr = str.replaceAll("[^a-z]", "").split("(?!^)");
        String[] nonEng = str.replaceAll("[A-Za-z]", "").split("(?!^)");
        System.out.println("Printout uppercase");
        printResult(upStr);
        System.out.println("\nPrintout lowercase");
        printResult(lowStr);
        System.out.println("\nPrintout non-English");
        printResult(nonEng);   
    }
public static void printResult(String[] array) {
        for (String outChar : array){
        System.out.print(outChar);
    }
    System.out.println("\n" + array.length);
}

输出:

Printout uppercase
AABBBBCCOOHA
12

Printout lowercase
aaaccadfsfdkkha
15

Printout non-English
&^%99876 _
10

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    • 2018-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多