如何迭代String(char [])

时间:2015-12-19 09:14:11

标签: java string

我将一个文件的内容读入String(char[]) content

8264,1
28462,1
15836,1

然后我想将第二列乘以5并附加另一个带有已处理值的文件:

8264,5
28462,5
15836,5

问题在于迭代content。如果我按下图所示进行迭代,那么显然我会得到8264等字符,而不是8264,5行。< / p>

FileWriter fw = new FileWriter(filew.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
StringBuilder sb = new StringBuilder();
for (int k = 0; k < content.length(); k++) 
{
    char c = content.charAt(k);
    //multiply second column by 5
} 

1 个答案:

答案 0 :(得分:0)

如果你想逐行迭代我会推荐一个扫描仪。

PrintWriter pw = new PrintWriter(...file/stream...);
Scanner sc = new Scanner(...your file/stream/string...);
while (sc.hasNextLine()) {
    String line = sc.nextLine();
    String[] parts = line.split(",");
    int first = Integer.parseInt(parts[0]);
    int second = Integer.parseInt(parts[1]);
    second *= 5;
    pw.println(first + "," + second);
}
sc.close();
pw.close();