字符串操作-删除第二个单词到第一个单词的字符

时间:2020-03-24 12:45:17

标签: java

输入两个词:计算机程序

结果:可爱

the character of the second word of the users input is deleted on the first word of the input in java. Leaving "cute" 想过使用replaceAll,但无法使其工作。

    String sentence;
    Scanner input = new Scanner(System.in);
    System.out.println("Enter 2 words: ");
    sentence = input.nextLine();

    String[] arrWrd = sentence.split(" ");

    String scdWrd = arrWrd[1];

    String fnl = arrWrd[0].replaceAll(scdWrd, "");

    System.out.println(fnl);

3 个答案:

答案 0 :(得分:1)

.replaceAll需要一个正则表达式,所以基本上您在这里要做的是搜索整个“程序”字词并替换它,而不是它的字符,因此您只需在方括号中添加括号即可。让它知道您要替换字符:

String scdWrd = "[" + arrWrd[1] + "]";

答案 1 :(得分:1)

只需添加@ B.Mik的优雅解决方案,您还应该检查类似内容

  1. 如果单词之间输入了多个空格。
  2. 如果用户输入空白行或仅输入一个单词,例如执行您的程序并输入空白行或仅输入一个单词,例如computer,欢迎您java.lang.ArrayIndexOutOfBoundsException

下面给出的程序解决了这些问题:

import java.util.Scanner;

public class LettersFromSecondReplacement {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        boolean valid;
        String input;
        String words[];
        do {
            valid = true;
            System.out.print("Enter two words separated with space: ");
            input = in.nextLine();
            words = input.split("\\s+"); //Split on one or more spaces
            if (words.length != 2) {
                System.out.println("Error: wrong input. Try again");
                valid = false;
            }
        } while (!valid);
        for (String s : words[1].split("")) { //Split the 2nd word into strings of one character
            words[0] = words[0].replaceAll(s, "");
        }

        System.out.println(words[0]);
    }
}

示例运行:

Enter two words separated with space: 
Error: wrong input. Try again
Enter two words separated with space: computer
Error: wrong input. Try again
Enter two words separated with space: computer program
cute

请注意,我使用了另一种算法(可以将其替换为@ B.Mik提供的算法)。如有任何疑问/问题,请随时发表评论

答案 2 :(得分:0)

用replaceAll替换行

    String fnl = arrWrd[0];
    for (byte c : scdWrd.getBytes()) {
        fnl = fnl.replace("" + (char)c, "");
    }