Home > Mobile >  How to split a user entered String into two different arrays
How to split a user entered String into two different arrays

Time:03-09

I would like to split a string into 2 different arrays with no leading or ending whitespace. One array for the word and another for the definition. The delimiter is "-".

The input from the user would be: "Ice cream - is a sweetened frozen food typically eaten as a snack or dessert"

However, I am having trouble splitting the string into the respective arrays so that it would be something like this

String sen1 = "Ice cream - is a sweetened frozen food typically eaten as a snack or dessert";

word[0] = "Ice cream"; definition[0] = "is a sweetened frozen food typically eaten as a snack or dessert";

How would I split or otherwise accomplish that?

CodePudding user response:

You could represent the words and definitions using a 2D string array. Here is one approach:

String[][] terms = new String[3][2];
String input = "Ice cream - is a sweetened frozen food typically eaten as a snack or dessert";
terms[0] = input.split("\\s*-\\s*");
System.out.println(Arrays.deepToString(terms));

This prints:

[[Ice cream, is a sweetened frozen food typically eaten as a snack or dessert],
 [null, null],
 [null, null]]

CodePudding user response:

Try the below code:

    String sen1 = "Ice cream - is a sweetened frozen food typically eaten as a snack or dessert";
    String[] split = sen1.split("-"); // splitting by '-'
    String[] words = new String[1];
    String[] definitions = new String[1];
    words[0] = split[0].trim(); // trim used to remove before and after spaces
    definitions[0] = split[1].trim();
  • Related