pyzor
pyzor

Reputation: 191

splitting string by spaces and new lines

I'm trying to split a string into an array. This should be fine as str.split(" ") should work fine, however the string is actually in the form of "xyz 100b\nabc 200b\ndef 400b". I'm wondering what the best way to handle this is. I also need to return 4 strings in the format they gave. Below is how I'm trying it now, but it's not splitting the array up correctly. My goal is to get the array split to ["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";

}

EDIT:

String array [] = str.split("\n| ") will split the array as I needed, thank you A.Oubidar

Upvotes: 0

Views: 1601

Answers (3)

A.Oubidar
A.Oubidar

Reputation: 401

I hope i understood your question right but if you're looking to extract the number and return them in the specific format you could go like this :

    // 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);

This is the value of answer after execution :

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

Upvotes: 2

rzwitserloot
rzwitserloot

Reputation: 102813

  1. The split() method takes one regular expression as argument. This: input.split("\\s+") will split on whitespace (\s = space, + = 1 or more).

  2. Your question is unclear, but if you're supposed to extract the '100', '200', etc, regular expressions are also pretty good at that. You can throw each line through a regular expression to extract the value. There are many tutorials (just google for 'java regexp example').

Upvotes: 1

evening_g
evening_g

Reputation: 173

You should put this code in the "return" instead of the one you already have:

    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";

Upvotes: 1

Related Questions