3

I have a TextArea with enter separated values:

For Example:

Value1

Value2

Value3

Value4

Value5

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

String[] newStringArray = ???
1
  • "new line separated values" would have been clearer than enter separated values Commented Jun 2, 2010 at 9:55

2 Answers 2

7

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

String[] values = textArea.getText().split("\n");
Sign up to request clarification or add additional context in comments.

2 Comments

Use .split("\n+") if the values can be separated by empty lines as well.
+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.
5

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>

1 Comment

The DefaultEditorKit documentation (java.sun.com/javase/6/docs/api/javax/swing/text/…) would suggest that line endings from a TextArea are normalized to '\n'.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.