【问题标题】:How do I split a line into pieces when there are different delimiters? Java [duplicate]当有不同的分隔符时,如何将一条线分成几部分? Java [重复]
【发布时间】:2021-12-15 18:17:10
【问题描述】:

我正在使用 java 中的计算器。我有一种方法可以将用户输入作为字符串解析为双精度数组。我接受一个字符串,并使用一个以“+”作为分隔符的拆分方法将其转换为双精度数组。此代码仅适用于加法操作。这是代码:

public static double[] parseInput(String input){
        
//      creates a String array that contains the elements of the input without the plus signs       
        String [] pieces = input.trim().split("\\+");
//      creates a double array the same size as the string array previous to this
        double[] nums = new double [pieces.length];
//      loops through each index of the string array, parses and places the element into the double array
        for(int i = 0; i < nums.length; i++){
            nums[i] = Integer.parseInt(pieces[i]);
        }
//      returns the double array
        return nums;
        
    }

我还需要让它适用于其他操作,例如减法、乘法等...我还需要让它适用于用户在同一行中执行多个操作时,例如 1+3- 2.

我并不担心其中的数学部分,只担心解析。底线是这样的。我需要创建一个数组,其中包含正在操作的数字以及操作。

如果我们可以让它与数字之间的空格一起工作,那就加分了。此代码目前适用于“1+1”,但适用于“1 + 1”。

提前谢谢你。

【问题讨论】:

标签: java arrays methods split


【解决方案1】:
input: 
 double[] spacesNum = parseInput("4- 8 +3- 12* 34/ 45");

parser: 
String [] pieces = input.trim().replaceAll("\\s+", "").split("[-+*/]");

【讨论】:

  • 虽然此代码可能会回答问题,但提供有关它如何和/或为什么解决问题的额外上下文将提高​​答案的长期价值。您可以在帮助中心找到更多关于如何写好答案的信息:stackoverflow.com/help/how-to-answer。祝你好运?
【解决方案2】:
String str = "word1, word2 word3@word4?word5.word6";
String[] arrOfStr = str.split("[, ?.@]+");
 
for (String a : arrOfStr)
    System.out.println(a);

会给:

word1
word2
word3
word4
word5
word6

这应该会给你想要的结果

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-06-22
    • 2018-09-25
    • 1970-01-01
    • 2021-04-05
    • 2018-09-24
    • 2017-11-09
    • 1970-01-01
    相关资源
    最近更新 更多