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

标签 java string loops

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

相关文章:

java - 将对象存储在数组中并显示它们(Java)

c - 通过转换为 char* 并在 sprintf 中使用 "%s"来打印十六进制整数

java - 遍历所有 SimpleTextBox

r - R中的高效循环逻辑回归

java - 如何在获取最后位置时解决 mLastLocation、mLatitudeText、mLongitudeText

java - SAML 元数据条目的签名信任建立失败

java - 如何创建控制复选框显示的自定义模型?

javascript - 将状态设置为空字符串不会为我触发重新渲染?

javascript - 字符串在 JavaScript 中如何工作?

java - JAVA组合生成器