Home > Back-end >  Split a phrase into multidimesional array of characters
Split a phrase into multidimesional array of characters

Time:11-12

I have a String that contains a phrase inputted by the user:

import java.util.Scanner;
public class eldertonguetranslator
{
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        String inputtext;
        System.out.println("Enter you text: ");
        inputtext = sc.nextLine();
    }
}

Right now an example value of that string is:

lorem ipsum

How would I go about diving each word of that string into an array of individual characters?

So that is would be like this:

char[][] splittext = { {l, o , r, e, m}, {i, p, s, u, m} };

Remember that the number of words in the phrase, and how many letters are in that word will change every time.

Thank you all so much for the help!

CodePudding user response:

Try this:

char[][] wordsAsChars = Arrays.stream(str.split(" "))
  .map(String::toCharArray)
  .toArray(char[][]::new);

This streams the words found by splitting the input on spaces, converting each word to its char[] equivalent, then collects the char[] into a char[][].

String#split() accepts a regex (in this case just a plain space character) and returns a String[].

Arrays.stream() streams the elements of an array.

  • Related