开发者

Get array from enter separated values

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 = ???


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

String[] values = textArea.getText().split("\n");


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>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜