好的,我正在编写这段代码来融合人文学科和 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/