【问题标题】:Repeating string inside loop循环内重复字符串
【发布时间】:2016-11-26 18:59:02
【问题描述】:

我正在尝试使用拆分功能从文件(即contact.txt)中读取contact nameemailmobile number。所以我使用\n"<space>" 将所有这些字符串捕获到数组中。

在我的文件contact.txt中,数据如下:

name1 email1 mobile_1
name2 email2 mobile_2
name3 email3 mobile_3
name4 email4 mobile_4
name5 email5 mobile_5
name6 email6 mobile_6

我的代码如下:

String usersInfo;

BufferedReader br = new BufferedReader(new FileReader("C:/contact.txt"));
try {
    StringBuilder sb = new StringBuilder();
    String line = br.readLine();

    while (line != null) {
        sb.append(line);
        sb.append(System.lineSeparator());
        line = br.readLine();
    }
    usersInfo = sb.toString();
} finally {
    br.close();
}


String[] splitStrNewLine = usersInfo.split("\n");
String[] splitStrSpace = usersInfo.split("[ \n]");


for(int i=0; i<=5; i++){
    for(int j=0; j<=2; j++){
        System.out.println(splitStrSpace[j]);
    }
}

现在它开始以循环方式重复输出相同的字符串,输出如下:

name1
email1
mobile_1

name1
email1
mobile_1

name1
email1
mobile_1

name1
email1
mobile_1

name1
email1
mobile_1

name1
email1
mobile_1

请告诉我,如何明智地检索我的所有数据系列?

我们将不胜感激,提前致谢!

【问题讨论】:

  • 底部的循环似乎根本没有使用i 索引
  • 在这种情况下我应该使用什么?
  • 为什么不直接在while循环中拆分联系信息?

标签: java string loops split


【解决方案1】:

在 try 块之后试试这个

String[] splitStrNewLine = usersInfo.split("\n");

fileLength = splitStrNewLine.length();

for(int i=0; i<fileLength; i++){
    splitStrSpace = splitStrNewLine[i].split("[ ]"); \\specify delimiter you want to split
    for(int j=0; j<splitStrSpace.length(); j++){
        System.out.println(splitStrSpace[j]);
    }
}

【讨论】:

    【解决方案2】:

    我可以建议您继续使用真正的集合结构吗?您正在使用 readLine 来获取行。为什么要将它们与插入的字符一起粘贴回来,然后需要再次解析?

    List<String> usersInfo = new ArrayList<String>()
    BufferedReader br = new BufferedReader(new FileReader("C:/contact.txt"));
    try {
        String line = br.readLine();
        while (line != null) {
            lines.add(line);
            line = br.readLine();
        }
    } finally {
        br.close();
    }
    

    现在您有了一个易于迭代的结构,并且您将每一行都恢复为原来的样子。现在,只需迭代这些行,并根据需要拆分每一行:

    for(String line : userInfo){
        String[] splitStrSpace = line.split("[ ]");
        for(int j=0; j<=splitStrSpace.length; j++){
            System.out.println(splitStrSpace[j]);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-28
      • 2021-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多