考虑到这些条件,我试图在不同的行中返回字符串。由于我不能在字符串中使用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;
}
答案 0 :(得分:1)
每次都在循环中重新初始化字符串。移动字符串声明outid eof loop:
替换此
String newstring = '\n' + text.substring(index2,index1);
带
result = '\n' + text.substring(index2,index1);
答案 1 :(得分:1)
修改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()
,但我强烈赞成+=
简洁明了。可读的。
答案 2 :(得分:0)
首先,使用StringBuilder。
其次,使用System.getProperty(“line.separator”)来确保使用正确的换行符。
编辑代码:
public String allWordsWith(char letter)
{
StringBuilder sb = new StringBuilder();
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);
sb.Append(text.substring(index2,index1));
sb.Append(System.getProperty("line.separator"));
//I put the new line after the word so you don't get an empty
//line on top, but you can do what you need/want to do in this case.
}
i++;
}
return result;
}
答案 3 :(得分:0)
使用StringBuilder
如下:
public String allWordsWith(char letter){
//String result = "";
StringBuilder result = new StringBuilder();
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);
result.append('\n' + text.substring(index2,index1));
}
i++;
}
return result.toString();
}
答案 4 :(得分:0)
String text = "I have android code with many different java, bmp and xml files everywhere in my project that I used during the drafting phase of my project.";
String letter = "a";
Set<String> duplicateWordsFilter = new HashSet<String>(Arrays.asList(text.split(" ")));
StringBuilder sb = new StringBuilder(text.length());
for (String word : duplicateWordsFilter) {
if (word.contains(letter)) {
sb.append(word);
sb.append("\n");
}
}
return sb.toString();
结果是:
android
have
java,
drafting
and
many
that
phase