提问者:小点点

Java字符串使用管道|分割多个分隔符


我试图将字符串b="x yi"分解为两个整数x和y。

这是我最初的答案。在这里,我用子串方法删除了尾随的“i”字符:

int Integerpart = (int)(new Integer(b.split("\\+")[0]));
int Imaginary = (int)(new Integer((b.split("\\+")[1]).
                      substring(0, b.split("\\+")[1].length() - 1)));

但是我发现下面的代码是一样的:

int x = (int)(new Integer(a.split("\\+|i")[0]));
int y = (int)(new Integer(a.split("\\+|i")[1]));

|有什么特别之处吗?我查了留档和许多其他问题,但我找不到答案。


共2个答案

匿名用户

拆分()方法采用控制拆分的正则表达式。尝试“[i]”。大括号标记一组字符,在本例中为“”和“i”。

然而,这不会完成你正在尝试做的事情。你最终会得到一些“b=x”、“y", "". 正则表达式也提供搜索和捕获功能。看看字符串.匹配(字符串正则表达式)。

匿名用户

您可以使用给定的链接来了解分隔符的工作原理。

如何在扫描仪中使用Java分隔符?

另一种替代方式

您可以使用Scanner类的useDendimiter(String模式)方法。Scanner类的useDendimiter(String模式)方法的使用。基本上我们已经使用了String分号(;)来标记Scanner对象的构造函数上声明的String。

字符串“Anne Mills/女性/18”上有三个可能的标记,即姓名、性别和年龄。扫描仪类用于拆分字符串并在控制台中输出标记。

import java.util.Scanner;

/*
 * This is a java example source code that shows how to use useDelimiter(String pattern)
 * method of Scanner class. We use the string ; as delimiter
 * to use in tokenizing a String input declared in Scanner constructor
 */

public class ScannerUseDelimiterDemo {

    public static void main(String[] args) {

        // Initialize Scanner object
        Scanner scan = new Scanner("Anna Mills/Female/18");
        // initialize the string delimiter
        scan.useDelimiter("/");
        // Printing the delimiter used
        System.out.println("The delimiter use is "+scan.delimiter());
        // Printing the tokenized Strings
        while(scan.hasNext()){
            System.out.println(scan.next());
        }
        // closing the scanner stream
        scan.close();

    }
}

相关问题