Jasper1378
Jasper1378

Reputation: 33

Split a phrase into multidimesional array of characters

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!

Upvotes: 0

Views: 91

Answers (1)

Bohemian
Bohemian

Reputation: 424993

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.


The reverse of the process, ie taking a char[][] and producing a sentence, is:

String sentence = Arrays.stream(wordsAsChars)
  .map(String::new)
  .collect(Collectors.joining(" "));

.map(String::new) invokes the String​(char[] value) constructor.

joining(" ") joins all elements of a String stream, separating them with a space

Upvotes: 1

Related Questions