删除每个单词Java末尾的字母“ e”

时间:2018-06-22 05:46:23

标签: java arrays string

需要帮助。如果单词长度> 1,则删除每个单词末尾的字母“ e”。 我试图通过strig split和toCharArray来做到这一点,但是删除字符串后我无法转换数组。 预先谢谢你。

public class RemoveE {
    public static void main(String args[]) {
        String str = "like row lounge dude top";
        String[] words = str.split("\\s|[,.;:]");
        for (String subStr : words) {
            if (subStr.endsWith("e"))
                subStr = subStr.substring(0, subStr.length() - 1);
            String finalString = new String(subStr);
            System.out.println(finalString);
        }
}
}

4 个答案:

答案 0 :(得分:7)

如果您通过这样的正则表达式进行操作会更简单

finalString = str.replaceAll("e\\b", "");

这给出了以下输出:

lik row loung dud top

PS:此解决方案假定您甚至希望在字符串中丢弃单个e,因为在此问题中,我们使用的是if (subStr.endsWith("e")),这也会删除单个{{1 }}。

答案 1 :(得分:3)

对于您的代码,所有拆分条件和if条件都是正确的,您需要做的就是在处理完成后将subStr添加到finalString。我从您的代码中重新排列了3行,您可以在注释中找到解释:

public class RemoveE {
    public static void main(String args[]) {
        String str = "like row lounge dude top";
        String[] words = str.split("\\s|[,.;:]");

        String finalString = ""; // Bring the declaration outside of for loop

        for (String subStr : words) {
            if (subStr.endsWith("e"))
                subStr = subStr.substring(0, subStr.length() - 1);
            finalString += subStr + " "; // Add the substring and a whitespace to substring and add it to finalString to create the sentence again
        }

        System.out.println(finalString); // Print the String outside of final `for` loop
    }
}

这将提供以下输出:

lik row loung dud top 

答案 2 :(得分:3)

拉曼的第一个答案为使用正则表达式的解决方案提供了一个良好的开端。但是,要确保仅在单词本身具有多个字符的情况下才丢弃e,您可以在其后面添加否定的后缀,以确保在单词{<之前>立即之前没有单词边界{1}}与e

(?<!\\b)

答案 3 :(得分:1)

此解决方案不包含regex。将其添加为参考,因为这将来可能也会有所帮助。

我猜想,因为创建了一个新的char数组并使用了简单的for循环来迭代输入字符串并将有效的char保留在新的{{1}中,所以不需要解释}通过检查条件将其放置在适当的位置。

char
  

对于public class RemoveE { public static void main (String[] args) { String str = "like row lounge dude top"; char[] strChars = str.toCharArray(); int size = str.length(); int temp = 0; char[] newStringChars = new char[size]; String newString = null; newStringChars[0] = strChars[0]; for(int i=1; i<size; i++) { if(!(strChars[i] == 'e' && strChars[i+1] == ' ')) { temp++; newStringChars[temp] = strChars[i]; } else if(strChars[i] == 'e' && strChars[i+1] == ' ' && strChars[i-1] == ' ') { temp++; newStringChars[temp] = strChars[i]; } else { continue; } } newString = String.valueOf(newStringChars); System.out.println(newString); } } 的输出是:

String str = "like row lounge dude top";

AND

  

对于lik row loung dud top (仅存在一个String str = "like row e lounge dude top";)   一句话,即不是问题中提到的e,   输出是:

word length > 1
相关问题