在给定这些条件的情况下,我尝试在不同的行中返回字符串。由于我无法在 Java 中将 += 与字符串一起使用,因此如何制作一个每行间隔但“堆栈”的巨型字符串?换句话说,如何在循环中将新字符串添加到旧字符串中?
/**
Returns a String that concatenates all "offending"
words from text that contain letter; the words are
separated by '\n' characters; the returned string
does not contain duplicate words: each word occurs
only once; there are no punctuation or whitespace
characters in the returned string.
@param letter character to find in text
@return String containing all words with letter
*/
public String allWordsWith(char letter)
{
String result = "";
int i = 0;
while (i < text.length())
{
char newchar = text.charAt(i);
if (newchar == letter)
{
int index1 = text.lastIndexOf("",i);
int index2 = text.indexOf("",i);
String newstring = '\n' + text.substring(index2,index1);
}
i++;
}
return result;
}
最佳答案
修改结果
字符串,并修复您的“单词边界”测试。
if (newchar == letter) {
int index1 = text.lastIndexOf(' ',i);
int index2 = text.indexOf(' ',i);
// TODO -- handle when index1 or index2 is < 0; that means it wasn't found,
// and you should use the string boundary (0 or length()) instead.
String word = text.substring( index2,index1);
result += "\n" + word;
}
如果您真的关心性能,您可以使用 StringBuilder
和 append()
,但除此之外,我强烈支持 +=
简洁易读。
关于java - 将添加的字符串返回到,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19263554/