字符串到字符串[]-Apache



我是一名学生,刚开始用java编程。我发现的这段代码有一个问题(我没有写),我想知道如果可能的话,我不太了解apache库,如果你能从这个方法String[]而不是单个字符串中得到一个。

public static String getString() throws IOException {
    String content = null;
    File folder = new File("E:\Result.txt");
    content = FileUtils.readFileToString(folder) + "n";
    String remainingString = content.substring(content.indexOf("["),
            content.lastIndexOf("]") + 1);
    // System.out.println(remainingString);
    return remainingString;
}

为了清楚起见,Result.txt的内容是一个字符串。(例如[-8,6,1][4,10,-1][7,-5,3][10,-8.3][10,-8,-6])。我的问题是:我希望保持字符串的相同格式(在result.txt中),但将其与string[]数组一起使用。非常感谢

看看这个

字符串分割方法

是否要获取所有[<content>]块;然后你只想添加它们,直到你无法读取下一个块:

public static String getString() throws IOException {
    File folder = new File("E:\Result.txt"); // such a strange name for variable with text file
    String content = FileUtils.readFileToString(folder);
    List <String> strs = new ArrayList<>();
    int lastIndex = 0;
    while (lastIndex != -1) {
        int i1 = content.indexOf('[', lastIndex);
        int i2 = content.indexOf(']', lastIndex) + 1;
        if (i1 != -1 && i2 != 0) {
            strs.put(content.substr(i1, i2));
            lastIndex = i2;
        } else {
            lastIndex = -1;
        }
    }
    return strs.toArray(new String[0]);
}

最新更新