views:

59

answers:

2

I have a TextArea with enter seperated values:

For Example:

Value1

Value2

Value3

Value4

Value5

Is there a fast way to put them in a String array

String[] newStringArray = ???
+2  A: 

You want to use String.split(String regex):

Returns: the array of strings computed by splitting this string around matches of the given regular expression

So, perhaps something like this:

String[] newStringArray = textAreaContent.split("\n");

This splits textAreaContent string around matches of "\n", which is the normalized newline separator for Swing text editors (as specified in javax.swing.text.DefaultEditorKit API):

[...] while the document is in memory, the "\n" character is used to define a newline, regardless of how the newline is defined when the document is on disk. Therefore, for searching purposes, "\n" should always be used.

The regular expression can always be worked out for your specific need (e.g. how do you want to handle multiple blank lines?) but this method does what you need.


Examples

    String[] parts = "xx;yyy;z".split(";");
    for (String part : parts) {
        System.out.println("<" + part + ">");   
    }

This prints:

<xx>
<yyy>
<z>

This one ignores multiple blank lines:

    String[] lines = "\n\nLine1\n\n\nLine2\nLine3".trim().split("\n+");
    for (String line : lines) {
        System.out.println("<" + line + ">");           
    }

This prints:

<Line1>
<Line2>
<Line3>
polygenelubricants
The `DefaultEditorKit` documentation (http://java.sun.com/javase/6/docs/api/javax/swing/text/DefaultEditorKit.html) would suggest that line endings from a `TextArea` are normalized to `'\n'`.
jasonmp85
@polygenelubricants: vote added! :-P
jasonmp85
+5  A: 

Use String.split(). If your TextArea is named textArea, do this:

String[] values = textArea.getText().split("\n");
jasonmp85
Use `.split("\n+")` if the values can be separated by empty lines as well.
Joachim Sauer
+1. `String.split()` takes a regex as its first argument. If you've not come across them before, they're well worth learning. It's something I resisted learning for a while and now that I know them well I use them every single day.
jasonmp85