Java 如何拆分单词并用某个字母分隔单词?

Java 如何拆分单词并用某个字母分隔单词?,java,split,Java,Split,在我的程序中,我想从用户那里获取一个输入,用字母e分隔单词,并将它们连接在一起,不留任何空格或不同的行。例如,如果我的输入是Rob是一个好人,我希望它打印出一个好人。这就是我到目前为止所做的: Scanner kybd = new Scanner(System.in); String s = kybd.nextLine(); String[] arr = s.split(" "); for ( String ss : arr) { String []ary = {ss};

在我的程序中,我想从用户那里获取一个输入,用字母e分隔单词,并将它们连接在一起,不留任何空格或不同的行。例如,如果我的输入是Rob是一个好人,我希望它打印出一个好人。这就是我到目前为止所做的:

Scanner kybd = new Scanner(System.in);
String s = kybd.nextLine();
String[] arr = s.split(" ");    
for ( String ss : arr) {
    String []ary = {ss};
    for(int i = 0; i < ss.length(); i++){
        if(ary[i].equalsIgnoreCase("e")){
            System.out.print(ary);
        }
    }
}
谢谢你的提示和帮助

使用该方法,其工作原理如下:

Scanner kybd = new Scanner(System.in);
StringBuilder result = new StringBuilder();
String s = kybd.nextLine();
String[] arr = s.split(" ");
 for ( String ss : arr) {
     if(ss.contains("e")) {
         result.append(ss);
     }
}
使用该方法,其工作原理如下:

Scanner kybd = new Scanner(System.in);
StringBuilder result = new StringBuilder();
String s = kybd.nextLine();
String[] arr = s.split(" ");
 for ( String ss : arr) {
     if(ss.contains("e")) {
         result.append(ss);
     }
}

你可以这样做

    String str = "Rob is a nice person";
    String[] arr = str.split(" "); // split by space
    StringBuilder sb = new StringBuilder();
    for (String i : arr) {
        if (i.contains("e")) { // if word contains e
         sb.append(i);// append that word 
        }
    }
    System.out.println(sb);
输出:

   niceperson

你可以这样做

    String str = "Rob is a nice person";
    String[] arr = str.split(" "); // split by space
    StringBuilder sb = new StringBuilder();
    for (String i : arr) {
        if (i.contains("e")) { // if word contains e
         sb.append(i);// append that word 
        }
    }
    System.out.println(sb);
输出:

   niceperson

比如string.replace,e;
我假设您使用的是String静态方法,正如我看到的,您使用的是Split

一些方法,比如String.replace,e; 我假设您使用的是字符串静态方法,因为我可以看到您使用的是Split

s = s.replaceAll("(\\b[\\w&&[^e]]+\\b)|\\s", "");
试试这个

s = s.replaceAll("(\\b[\\w&&[^e]]+\\b)|\\s", "");

有没有一种不使用contains方法的方法?这是一个作业,我们还没有了解到包含。我想使用我在代码中指定的方法。当然,为了学习起见,请先提示一下:不要使用contains if,而是使用charAtindex循环字符串的所有字符,只有在找到搜索的字母时才添加单词。如果没有append方法,您会建议另一种方法吗?抱歉,我忘了指出我也不知道那个方法…只需将结果声明为字符串,并使用普通字符串连接,如result=result+ss@Merguez,即使你的答案已经有两张赞成票,我还是给了你另一张,因为你的答案是如此的有用和亲切!有没有一种不使用contains方法的方法?这是一个作业,我们还没有了解到包含。我想使用我在代码中指定的方法。当然,为了学习起见,请先提示一下:不要使用contains if,而是使用charAtindex循环字符串的所有字符,只有在找到搜索的字母时才添加单词。如果没有append方法,您会建议另一种方法吗?抱歉,我忘了指出我也不知道那个方法…只需将结果声明为字符串,并使用普通字符串连接,如result=result+ss@Merguez,即使你的答案已经有两张赞成票,我还是给了你另一张,因为你的答案是如此的有用和亲切!