从输入分隔值获取数组

发布于 2024-09-04 15:27:26 字数 210 浏览 1 评论 0原文

我有一个带有输入分隔值的 TextArea

例如:

Value1

Value2

Value3

Value4

Value5

是否有一种快速方法将它们放入 String 数组中

String[] newStringArray = ???

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

世态炎凉 2024-09-11 15:27:26

使用 String.split()。如果您的 TextArea 名为 textArea,请执行以下操作:

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

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

String[] values = textArea.getText().split("\n");
北城孤痞 2024-09-11 15:27:26

您想使用 String.split(字符串正则表达式):

返回:通过将此字符串拆分为给定正则表达式的匹配项而计算出的字符串数组

因此,也许是这样的:

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

这会围绕 " 的匹配拆分 textAreaContent 字符串\n",这是 Swing 文本编辑器的标准化换行符(如 javax.swing.text.DefaultEditorKit API):

[...] 当文档在内存中时,"\n" 字符用于定义换行符,无论文档在磁盘上时如何定义换行符。因此,出于搜索目的,应始终使用 "\n"

正则表达式始终可以根据您的特定需求(例如,您想如何处理多个空行?)来计算,但此方法可以满足您的需要。


示例

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

这会打印:

<xx>
<yyy>
<z>

这会忽略多个空行:

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

这会打印:

<Line1>
<Line2>
<Line3>

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>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文