![](/img/trans.png)
[英]replace string(no of characters) in another string from given starting index to given end index
[英]Java StringBuffer: replace the content from a starting index to the end of a line
我在StringBuffer中有文件的内容。 文件的内容包括很多行(不在一行上)。 我想编辑从索引4(例如)到该行末尾的行的内容。 我使用replace()
编辑StringBuffer的内容。
关键是替换方法具有诸如开始索引和结束索引的参数。 但是我不知道结束索引是什么,因为每一行都有不同数量的字符
我认为可以使用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
}
按照您的指示使用String.indexOf()
,但是将其传递到起始位置,例如indexOf('\\n', 4);
我同意Jim的想法,为什么不将字符串附加到StringBuffer之前先处理它。
顺便说一句,我认为您可以使用indexOf(String str, int fromIndex)
函数来解析StringBuffer,并且每次获取'\\n'
,都可以设置一个偏移值,然后在下次获取下一个\\n
,您可以只让索引值加上偏移量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.