首页 > 解决方案 > 字符串操作 - 将第二个单词的字符删除到第一个单词

问题描述

输入两个字:计算机程序

结果:可爱

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);

标签: java

解决方案


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

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

推荐阅读