【问题标题】:How can I split String array with following delimiters in java如何在java中使用以下分隔符拆分字符串数组
【发布时间】:2018-07-13 08:02:56
【问题描述】:

我在输入文件中有一行。 安排如下(示例):

(space)MOV(space)A,(space)(space)#20

当计算机正在读取这一行时,我打算将这个字符串拆分()并添加到数组中。我为此使用以下代码:

while((nline = bufreader.readLine()) != null)
{
    String[] array = nline.split("[ ,]");

换句话说,字符串用分隔符分隔:(空格)和(逗号)。所以,我希望我的数组长度为 3。但实际上我得到 6。

因此,据我了解,计算机创建了 {"(space)", "MOV", "(space)", "A", "(space)", "(space)", "#20"} 数组。但是,我需要这个数组:{"MOV", "A", "#20"}

我怎样才能得到这个?或者如何根据上述分隔符拆分数组。 (我想nline.split("[ ,]") 是不正确的)。

【问题讨论】:

  • 我会使用正则表达式直接抓取数据。
  • 逗号之间好像有多个空格。您可以拆分 , 然后 trim 每个结果以删除额外的前导和尾随空格。
  • @BeybarsMusagaliyev 我编辑了我的答案以使其涵盖您对问题的所有期望。

标签: java arrays string split


【解决方案1】:

我把注释中的所有解释都放到了适当的行,看看这个:

String nline;
BufferedReader bufreader = new BufferedReader(new FileReader(new File("nameOfYourFile")));
while((nline = bufreader.readLine()) != null) {
    String trimmed = nline.trim(); // removing leading and trailing spaces
    // System.out.println(trimmed); Output from this line: >>MOV A,  #20<< (">>" and "<<" just to show where it begins and ends)
    String[] splitted = trimmed.split("[ |,]{1,}"); // split on ' ' OR ',' that appear AT LEAST once (so it also matches " ," (space + comma))
    System.out.println(Arrays.toString(splitted)); // Output: [MOV, A, #20]
}
bufreader.close();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-03
    • 2023-03-20
    • 2012-09-04
    • 2013-10-12
    • 1970-01-01
    • 1970-01-01
    • 2012-10-24
    • 1970-01-01
    相关资源
    最近更新 更多