尝试在用户输入的句子中找到所有四个字母的单词并替换它们,但代码不会执行任何操作



基本上,我需要一个代码片段来查找用户输入的句子中的所有4个字母的单词,并将它们替换为***。无论我怎么修改,我写的代码都不起作用。(例如,它不应该计算空格(

public class DisguiseWords {
static void count(String string) {
// Create an char array of given String
int j = string.trim().indexOf(" ");
while (j > 0) {
System.out.println(string.substring(0, j) + "-->> words " + j);
string = string.substring(j + 1).toString();
j = string.indexOf(" ");
}
if (string.length() == 4)
System.out.println("**** ");
}
}

String在与正则表达式组合时有一些非常方便的工具。

这个任务可以这样完成:

public static void main(String[] args) {
String sentence = "Hello this is the test sentence";
String newSentence = sentence.replaceAll("\b\w{4}\b", "****");
System.out.println(newSentence);
}

输出:

Hello **** is the **** sentence

说明:

replaceAll将取一个正则表达式,并将每个找到的匹配项替换为给定的替换项。正则表达式由以下部分组成:

  • b标记单词边界
  • w{4}表示有4位数字的单词

您可以通过将字符串拆分为一个字符串数组,然后检查每个项目是否为4个字母来完成,如下所示:

import java.util.Scanner;
public class MyClass {
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
String[] items = input.split(" ");
StringBuilder str = new StringBuilder();
for(int i = 0; i < items.length; i++){
if(items[i].length()==4){
str.append("****");
}else{
str.append(items[i]);
}
str.append(" ");
//Appends the space that was rid of during the .split()
}
System.out.println(str.toString());
}
}

测试运行

输入

This sentence is sort of interesting

输出

**** sentence is **** of interesting 

如果你不想使用正则表达式,但也想收集4个字母的世界,你可以这样做:

import java.util.*; 
import java.util.stream.*; 
class Playground {
public static void main(String[ ] args) {
String sentence = "This is a sentence with some four letter words, like this word.";
String sentenceWithoutPunctuation = sentence.replaceAll("[^a-zA-Z ]", "").toLowerCase();
String[] words = Arrays.stream(sentenceWithoutPunctuation.split(" "))
.filter(word -> word.length() == 4)
.toArray(String[]::new);
for (int i = 0; i < words.length; i++) {
sentence = sentence.replaceAll(words[i], "****");
}
System.out.println(sentence);
}
}

最新更新