gpt4 book ai didi

java - 将添加的字符串返回到

转载 作者:行者123 更新时间:2023-12-02 06:39:49 25 4
gpt4 key购买 nike

在给定这些条件的情况下,我尝试在不同的行中返回字符串。由于我无法在 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;
}

如果您真的关心性能,您可以使用 StringBuilderappend(),但除此之外,我强烈支持 +=简洁易读。

关于java - 将添加的字符串返回到,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19263554/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com