java—试图在用户输入的句子中找到所有四个字母的单词并替换它们,但代码却无能为力

wfsdck30  于 2021-07-07  发布在  Java
关注(0)|答案(3)|浏览(198)

基本上,我需要一个代码片段,找到所有的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("****");
    }
}
umuewwlo

umuewwlo1#

如果不想使用正则表达式,但又想收集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);
    }
}
x0fgdtte

x0fgdtte2#

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} 意思是一个四位数的单词

b5buobof

b5buobof3#

您可以将字符串拆分为字符串数组,然后检查每个项是否为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

相关问题