0

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?

  • 1
    Splitting a String in java is unsurprisingly done by using the `split` method of the String class: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html#split(java.lang.String) – OH GOD SPIDERS Mar 09 '22 at 08:57
  • 1
    Does this answer your question? [How to split a string in Java](https://stackoverflow.com/questions/3481828/how-to-split-a-string-in-java) – OH GOD SPIDERS Mar 09 '22 at 08:57

2 Answers2

0

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]]
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
0

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();
Prog_G
  • 1,539
  • 1
  • 8
  • 22