【问题标题】:splitting string by spaces and new lines用空格和换行符分割字符串
【发布时间】:2019-11-17 22:31:18
【问题描述】:

我正在尝试将字符串拆分为数组。这应该没问题,因为str.split(" ") 应该可以正常工作,但是字符串实际上是"xyz 100b\nabc 200b\ndef 400b" 的形式。我想知道处理这个问题的最佳方法是什么。我还需要以他们提供的格式返回 4 个字符串。下面是我现在尝试的方法,但它没有正确拆分数组。我的目标是将数组拆分为["xyz", "100b", "abc", "200b", "def", "400b"]

public static String solution(String words){
    String array[] = words.split(" ");

    /*
    There's a lot of other code manipulating the array to get 4 figures in the
    end. This doesn't matter, it's just splitting the array and the return that
    is my issue
    In the end I will have 4 integers that I want to return in a similar way
    that they gave them to me.
    */

    return "answer 1" + String.valueOf(num1) + "b\n" + 
           "answer2 " + String.valueOf(num2) + "b\n" +
           "answer 3" + String.valueOf(num3) + "b\n" + 
           "answer4 " + String.valueOf(num4) + "b\n";

}

编辑:

String array [] = str.split("\n| ") 将根据需要拆分数组,谢谢 A.Oubidar

【问题讨论】:

  • 你能用你目前尝试过的代码更新你的问题吗?
  • 对不起,我解释得很糟糕,这只是我试图寻求帮助的拆分和返回。 A.Oubidar 实际上给了我足够的答案

标签: java


【解决方案1】:

我希望我能正确理解您的问题,但如果您想提取数字并以特定格式返回它们,您可以这样:

    // Assuming the String would be like a repetition of [word][space][number][b][\n]
    String testString = "xyz 100b\nabc 200b\ndef 400b";

    // Split by both endOfLine and space
    String[] pieces = testString.split("\n| ");

    String answer = "";

    // pair index should contain the word, impair is the integer and 'b' letter
    for (int i = 0; i < pieces.length; i++) {
        if(i % 2 != 0 ) {
            answer = answer + "answer " + ((i/2)+1) + ": " + pieces[i] + "\n";
        }
    }
    System.out.println(answer);

这是执行后 answer 的值:

answer 1: 100b
answer 2: 200b
answer 3: 400b

【讨论】:

  • 原来它实际上只是我正在寻找的str.split("\n| "),谢谢!很抱歉让你做额外的工作:(
【解决方案2】:

您应该将此代码放在“return”中,而不是您已经拥有的代码:

    return "answer 1" + array[0] + "b\n" + 
       "answer 2 " + array[1] + "b\n" +
       "answer 3" + array[2] + "b\n" + 
       "answer 4 " + array[3] + "b\n";

【讨论】:

    【解决方案3】:
    1. split() 方法采用一个正则表达式作为参数。这:input.split("\\s+") 将在空格处拆分(\s = 空格,+ = 1 或更多)。

    2. 您的问题不清楚,但如果您要提取“100”、“200”等,正则表达式也很擅长。您可以通过正则表达式抛出每一行以提取值。有很多教程(只是谷歌'java regexp example')。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-22
      • 1970-01-01
      • 2014-10-04
      • 2022-01-17
      • 1970-01-01
      • 2022-07-06
      • 2014-12-13
      • 2013-08-02
      相关资源
      最近更新 更多