有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如何在Java中拆分字符串

我有一个字符串"004-034556",我想把它分成两个字符串:

string1="004";
string2="034556";

这意味着第一个字符串将包含'-'之前的字符,第二个字符串将包含'-'之后的字符。我还想检查字符串中是否有'-'。如果没有,我将抛出一个异常。我该怎么做


共 (6) 个答案

  1. # 1 楼答案

    // This leaves the regexes issue out of question
    // But we must remember that each character in the Delimiter String is treated
    // like a single delimiter        
    
    public static String[] SplitUsingTokenizer(String subject, String delimiters) {
       StringTokenizer strTkn = new StringTokenizer(subject, delimiters);
       ArrayList<String> arrLis = new ArrayList<String>(subject.length());
    
       while(strTkn.hasMoreTokens())
          arrLis.add(strTkn.nextToken());
    
       return arrLis.toArray(new String[0]);
    }
    
  2. # 2 楼答案

    使用:

    String[] result = yourString.split("-");
    if (result.length != 2) 
         throw new IllegalArgumentException("String not in correct format");
    

    这将把你的绳子分成两部分。数组中的第一个元素将是包含-之前的内容的部分,数组中的第二个元素将包含-之后的字符串部分

    如果数组长度不是2,则字符串的格式不是:string-string

    检查String类中的split()方法

  3. # 3 楼答案

    使用Java 8:

        List<String> stringList = Pattern.compile("-")
                .splitAsStream("004-034556")
                .collect(Collectors.toList());
    
        stringList.forEach(s -> System.out.println(s));
    
  4. # 4 楼答案

    这:

    String[] out = string.split("-");
    

    你应该做你想做的事。string类有许多方法可以使用字符串进行操作

  5. # 5 楼答案

    直接处理字符串的另一种方法是使用带有捕获组的正则表达式。这样做的优点是,可以直接对输入暗示更复杂的约束。例如,以下命令将字符串拆分为两部分,并确保两部分仅由数字组成:

    import java.util.regex.Pattern;
    import java.util.regex.Matcher;
    
    class SplitExample
    {
        private static Pattern twopart = Pattern.compile("(\\d+)-(\\d+)");
    
        public static void checkString(String s)
        {
            Matcher m = twopart.matcher(s);
            if (m.matches()) {
                System.out.println(s + " matches; first part is " + m.group(1) +
                                   ", second part is " + m.group(2) + ".");
            } else {
                System.out.println(s + " does not match.");
            }
        }
    
        public static void main(String[] args) {
            checkString("123-4567");
            checkString("foo-bar");
            checkString("123-");
            checkString("-4567");
            checkString("123-4567-890");
        }
    }
    

    由于模式在这个实例中是固定的,所以可以预先编译它并将其存储为静态成员(在示例中是在类加载时初始化的)。正则表达式是:

    (\d+)-(\d+)
    

    括号表示捕获组;匹配项可以访问与regexp的该部分匹配的字符串。方法,如图所示。\d匹配和一个十进制数字,+表示“匹配前面的一个或多个表达式”。-没有特殊含义,因此只匹配输入中的该字符。请注意,在将其作为Java字符串写入时,需要双转义反斜杠。其他一些示例:

    ([A-Z]+)-([A-Z]+)          // Each part consists of only capital letters 
    ([^-]+)-([^-]+)            // Each part consists of characters other than -
    ([A-Z]{2})-(\d+)           // The first part is exactly two capital letters,
                               // the second consists of digits
    
  6. # 6 楼答案

    只需使用适当的方法:^{}

    String string = "004-034556";
    String[] parts = string.split("-");
    String part1 = parts[0]; // 004
    String part2 = parts[1]; // 034556
    

    请注意,这需要一个regular expression,因此如果需要,请记住转义special characters

    there are 12 characters with special meanings: the backslash \, the caret ^, the dollar sign $, the period or dot ., the vertical bar or pipe symbol |, the question mark ?, the asterisk or star *, the plus sign +, the opening parenthesis (, the closing parenthesis ), and the opening square bracket [, the opening curly brace {, These special characters are often called "metacharacters".

    因此,如果您想在例如period/dot.上拆分,这在正则表达式中表示“any character”,请使用backslash ^{}转义单个特殊字符,如Sosplit("\\."),或使用character class ^{}表示文字字符,如Sosplit("[.]"),或使用^{}转义整个字符串,如Sosplit(Pattern.quote("."))

    String[] parts = string.split(Pattern.quote(".")); // Split on period.
    

    要预先测试字符串是否包含某些字符,只需使用^{}

    if (string.contains("-")) {
        // Split it.
    } else {
        throw new IllegalArgumentException("String " + string + " does not contain -");
    }
    

    注意,这不采用正则表达式。为此,请使用^{}

    如果希望在生成的部分中保留拆分字符,请使用positive lookaround。如果您想让拆分字符在左侧结束,请通过在模式上前缀?<=group使用正向查找

    String string = "004-034556";
    String[] parts = string.split("(?<=-)");
    String part1 = parts[0]; // 004-
    String part2 = parts[1]; // 034556
    

    如果希望拆分字符结束在右侧,请通过在模式上前缀?=group来使用正向前瞻

    String string = "004-034556";
    String[] parts = string.split("(?=-)");
    String part1 = parts[0]; // 004
    String part2 = parts[1]; // -034556
    

    如果您想限制结果部分的数量,那么可以提供所需的数量作为split()方法的第二个参数

    String string = "004-034556-42";
    String[] parts = string.split("-", 2);
    String part1 = parts[0]; // 004
    String part2 = parts[1]; // 034556-42