我想在给定这些条件的不同行中返回字符串。由于我不能在字符串中使用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;
}
关于使用StringBuilder的,这样就可以使用什么追加方法? – midhunhk
为什么你不能使用'+ ='?当然,使用'StringBuilder'更合理,但干草... – MadProgrammer
在上面的代码中,变量'newstring'在哪里使用。我认为用result ='\ n'+替换该行将会解决您的问题 – midhunhk