java - 我需要随机删除java中字符串中的一半单词

标签 java string

好的,我正在编写这段代码来融合人文学科和 STEM。我知道非常基本的 java 代码,所以我目前正在尝试坚持使用 String 方法。我知道使用数组可能更容易,但我不太了解如何使用它们。到目前为止,我已经编写了对字符串中的单词进行计数的代码,以确定要删除的单词数量(其中一半)。接下来我需要找出一种方法来随机删除一半的单词并返回一个新字符串,可能用空格替换删除的字母。

这是迄今为止我的代码:

public class wordcount
{
    public static void main (String[] args) 
    {

    System.out.println("Simple Java Word Count Program");

    String str1 = "Look, you want it you devour it and then, then good as it was you realize it wasn’t what you exactly wanted what you wanted exactly was wanting";

    String[] wordArray = str1.split("\\s+");
    int wordCount = wordArray.length;

    System.out.println(str1 + "");

    System.out.println("Word count is = " + wordCount);

    int wordCount2 = wordCount/2;


}

}

最佳答案

我将数组复制到 arrayList,然后迭代列表并删除随机元素。我希望这就是您正在寻找的答案。

public static void main(String[] args) {

    String str1 = "Look, you want it you devour it and then, then good as it was you realize it wasn’t what you exactly wanted what you wanted exactly was wanting";

    String[] wordArray = str1.split("\\s+");
    ArrayList<String> wordList = new ArrayList<String>(Arrays.asList(wordArray));

    int wordCount = wordList.size();
    int halfWordCount = wordCount/2;
    int tracker = 0; //counter for iterations in while loop

    Random random = new Random();
    while(tracker < halfWordCount){
        int randomIndex = random.nextInt(wordList.size());
        wordList.remove(randomIndex);
        tracker++;
    }
    System.out.println(wordList.toString());
}

关于java - 我需要随机删除java中字符串中的一半单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38757903/

相关文章:

java.net.UnknownHostException 在将日期更改为 future 之后发生

c++ - 在字符串的每个第 n 个元素之后插入字符(不使用 stringstream)

r - 将字符串转换为数据框

javascript - 查看字符串是否包含子字符串数组中的任何元素的最佳方法?然后如果匹配则替换

Java 中 getBytes 的 C# 模拟

java - 在 clojure 中处理 JavaOptional<T>

java.lang.IllegalArgumentException : argument type mismatch:when store the form values in Database 异常

python - 在python中以一定间隔从右边拆分一个字符串

java - Java 中的霍夫曼树

java - 旋转GeomeryUpdater不是抽象的并且不会重写抽象方法updateData(Geometry)?