user3120133
user3120133

Reputation: 13

I am trying to convert a string of words into an array with the spaces included

I want the user to input a name an actor: tom hanks

I am trying to convert the string "tom hanks" into an array.

However I want to keep the space in between the "m" and "t". so the array would read:

{"t","o", "m", " ", "h", "a", "n", "k", "s"}

Then the users input is compared against the answer in the program. letter by letter.

Considering the user will input a space, I am going to convert the string name into arrays and compare them like for like, with the space and all.

Here is the code i have so far

    String x;

    System.out.println("Please input a name");
    x = input.next(); 

    //the user enters in "tom hanks"

    String[] a = x.split("\\b");

This will only create the array {"t", "o", "m"}

Any help would be much appreciated it, thank you in advance.

Upvotes: 0

Views: 69

Answers (2)

rendon
rendon

Reputation: 2363

Use an empty string as the regex expression to split the string:

String str = "alan smith";
String[] letters = str.split("");

For example:

String str = "alan smith";
String[] letters = str.split("");
for (int i = 0; i < letters.length; i++)
    System.out.print(letters[i] + " ");

Output:

a l a n   s m i t h 

EDIT:

It seems that this method generate an empty token at the beginning.

Upvotes: 1

coder hacker
coder hacker

Reputation: 4868

You should convert your string to character array instead

char[] charArray = str.toCharArray();

You can access it like a normal array.

Upvotes: 3

Related Questions