【问题标题】:Java StringBuffer: replace the content from a starting index to the end of a lineJava StringBuffer:将内容从起始索引替换到行尾
【发布时间】:2012-11-04 13:05:04
【问题描述】:

我在 StringBuffer 中有一个文件的内容。该文件的内容包括多行(而不是单行)。我想编辑从索引 4(仅作为示例)到该行末尾的行的内容。我使用replace() 来编辑StringBuffer 的内容。

重点是replace方法有起始索引和结束索引等参数。但我不知道结束索引是什么,因为每一行的字符数不同

我想用str.indexOf("\n")找到行的结束索引,但是文件有很多行,所以会返回不正确的结果。

这是readFile(),如果您需要阅读代码

谢谢

public StringBuffer readFile(){ //read file line by line
    File f = getFilePath(fileName);
    StringBuffer sb = new StringBuffer();
    String textinLine;

    try {
        FileInputStream fs = new FileInputStream(f);
        InputStreamReader in = new InputStreamReader(fs);
        BufferedReader br = new BufferedReader(in);

     while (true){
            textinLine = br.readLine();
            if (textinLine == null) break;
            sb.append(textinLine+ "\n");
        }
        fs.close();
        in.close();
        br.close();
    } ... // just some catch statements heres
}

【问题讨论】:

  • 为什么不将您的更改单独应用到您读入的每一行,然后再附加到 StringBuffer 中? (顺便说一句,改用 StringBuilder 会更快)
  • b/c 我需要再次读取文件,所以我编写了一个读取文件并返回 StringBuffer 的方法...

标签: java replace stringbuffer


【解决方案1】:

按照您的指示使用String.indexOf(),但传入起始位置,例如indexOf('\n', 4);

【讨论】:

    【解决方案2】:

    我同意 Jim 的想法,为什么不在将字符串附加到 StringBuffer 之前对其进行处理。

    对了,我觉得你可以用indexOf(String str, int fromIndex)函数来解析StringBuffer,每次得到'\n'的时候,你可以设置一个偏移值,那么下次你得到下一个\n的时候,你可以让索引值加上偏移量。

    【讨论】:

      猜你喜欢
      • 2011-11-30
      • 2011-05-02
      • 1970-01-01
      • 2011-06-30
      • 2012-11-03
      • 1970-01-01
      • 1970-01-01
      • 2020-12-22
      • 1970-01-01
      相关资源
      最近更新 更多