代码之家  ›  专栏  ›  技术社区  ›  Stefanos Kargas

从输入分隔值获取数组

  •  3
  • Stefanos Kargas  · 技术社区  · 16 年前

    TextArea 使用“输入分隔值”:

    例如:

    Value1
    
    Value2
    
    Value3
    
    Value4
    
    Value5
    

    String 数组

    String[] newStringArray = ???
    
    2 回复  |  直到 11 年前
        1
  •  5
  •   polygenelubricants    16 年前

    你想用 String.split(String regex) :

    退货: 通过围绕给定正则表达式的匹配项拆分此字符串而计算的字符串数组

    所以,也许是这样的:

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

    这个分裂了 textAreaContent 把一根火柴串起来 "\n" 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>
    
        2
  •  7
  •   jasonmp85    16 年前

    使用 String.split() TextArea textArea ,请执行以下操作:

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