gpt4 book ai didi

java - 尝试从字符串中删除字符

转载 作者:行者123 更新时间:2023-12-02 03:13:58 25 4
gpt4 key购买 nike

我正在尝试从随机生成的 20 个字母单词中删除元音。我必须使用子字符串来完成这项作业,但在概念上我遇到了问题。使用此代码,单词的值永远不会改变并保持其原始值。当我对字符串的后半部分执行 i+2 时,它会跳转两个字符,并且当两个元音紧接着一个时,它会变得困惑。如果我必须使用子字符串,我怎样才能改进它每次都能工作。

public class WordsWithoutVowels {
String finalWord;

public WordsWithoutVowels(String word) {
for(int i = 0; i < 20; i++) {
if(word.charAt(i) == 'a') {word = word.substring(0, i) + word.substring(i++);}
if(word.charAt(i) == 'e') {word = word.substring(0, i) + word.substring(i++);}
if(word.charAt(i) == 'i') {word = word.substring(0, i) + word.substring(i++);}
if(word.charAt(i) == 'o') {word = word.substring(0, i) + word.substring(i++);}
if(word.charAt(i) == 'u') {word = word.substring(0, i) + word.substring(i++);}
if(word.charAt(i) == 'y') {word = word.substring(0, i) + word.substring(i++);}
System.out.println(word);
}
finalWord = word;
}

public String getWord()
{
return finalWord;
}
}

最佳答案

您可以使用下面的简化代码来执行此操作:

public static void main(String[] args) {
String stringPara = "this example will remove the vowals aeiou";
stringPara = removeCharFromString(stringPara, "a");
stringPara = removeCharFromString(stringPara, "e");
stringPara = removeCharFromString(stringPara, "i");
stringPara = removeCharFromString(stringPara, "o");
stringPara = removeCharFromString(stringPara, "u");
System.out.println(stringPara);
}

public static String removeCharFromString(String str, String characterToRemove){
while(str.contains(characterToRemove)){
str = str.substring(0, str.indexOf(characterToRemove)) + str.substring(str.indexOf(characterToRemove)+1, str.length()) ;
}
return str;
}

关于java - 尝试从字符串中删除字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40605066/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com