LuxuryWaffles
LuxuryWaffles

Reputation: 1708

Seperate Lines of words and store into array

I have this script from a txt file which I want to store into a list of arrays

the output can only contain % and numbers:

jump 1500
walk 50%
jump 1280

I want to store them in arrays like

string[] arr = {"jump", "1500"};

and add each of the array into a list,

how do I separate each line into a array and ignore lines that doesn't follow the format in the 2nd portion (% and numbers only)

Upvotes: 1

Views: 42

Answers (2)

Avalanche
Avalanche

Reputation: 386

Splitting the lines into an array:

List<String> list = new ArrayList<>();
// for each line ...
    // line is "jump 1500" for example
    String[] array = line.split(" ");
    list.add(array);
    // array => {"jump", "1500"}

To check if a String ONLY contains numbers and %, use a regex:

String line = "1500%";
if (line.matches("^[\\d\\%]*$") {
    // match!
}

The regex basically means the string start with, end with and only contains digits or %. Note that an empty string would match, if you want to enforce a min length of 1, use a + instead of *:

"^[\\d\\%]+$"

Upvotes: 2

Lin Yuan
Lin Yuan

Reputation: 538

Maybe you can try Regex to achieve this.

List saveList = new ArrayList();//List you want to keep result
String pattern = "[\\w]* (\\d*|\\d*%)";
String lineText = "jump 1280";//line text from your txt file
if (lineText.matches(pattern)) {
    saveList.add(lineText.split(" "));
}

Upvotes: 1

Related Questions