【发布时间】:2014-10-27 14:00:20
【问题描述】:
我希望能够将每一行添加到一个字符串中。 像这种格式 String = ""depends" line1 line2 line3 line4 line5 /depends""
所以本质上我想遍历每一行并从“depends”到“/depends”,包括它们在一个字符串中从头到尾。我该怎么做呢?
while(nextLine != "</depends>"){
completeString = line + currentline;
}
<depends>
line1
line2
line3
line4
line5
line6
</depends
【问题讨论】:
-
while(!"</depends>".equals(nextLine)) { -
旁注:使用 StringBuilder 而不是普通的字符串连接。它会更快,而且你不会用未使用的字符串浪费内存。
-
如果您使用的是 xml,您可以使用 dom 解析器。前任。 Dom4j
-
@stuXnet 需要注意的是,字符串连接在幕后使用了字符串生成器。
-
@DaveNewton 是也不是,iirc。实际上,
line + currentline会变成new StringBuilder().append(line).append(currentline).toString()或类似的东西,但Java 不会在所有迭代中使用相同的StringBuilder,而是每次都创建一个新的。所以如果你使用循环,你应该使用StringBuilder。
标签: java