0

I want to take in a String and split it every time I find a space. And then store each of these pieces into an array. Let's say I have this string:

String names = "amy bob lily harry luna james";

I also have this method declaration:

public static String[] seperateNames(String names) {
    String[] newNames;
    // Some code here
    return newNames[];
}

What would I fill this method with so I can get something like this:

newNames = {"amy", "bob", "lily", "harry", "luna", "james"};

What I think I should do is create a for-loop and inside it have an if-statement that can check if there's space. But I really don't know how to go about doing this. I also think I will need to use trim() after everything is stored in an array to remove spaces before and after each name stored in the array.

Any help or advice appreciated. Thanks!

Juan Carlos Mendoza
  • 5,736
  • 7
  • 25
  • 50
Viola
  • 33
  • 1
  • 1
  • 8

2 Answers2

0

To start you off on your assignment, String.split splits strings on a regular expression, this expression may be an empty string:

String[] ary = "abc".split("");
Yields the array:

(java.lang.String[]) [, a, b, c]

Getting rid of the empty 1st entry is left as an exercise for the reader :-)

Note: In Java 8, the empty first element is no longer included.

Engineero
  • 12,340
  • 5
  • 53
  • 75
0xe1λ7r
  • 1,957
  • 22
  • 31
  • 2
    Post taken from https://stackoverflow.com/questions/3413586/string-to-string-array-conversion-in-java – 0xe1λ7r Sep 27 '17 at 15:00
0
public static String[] seperateNames(String names) {
    return names.split(" ");
}
  • Welcome to SO! It's usually helpful to throw a quick explanation of the code and not just the code itself. Even if it's simple like above. – sniperd Sep 27 '17 at 15:14