因此,我几乎不学习Java,而使用循环却很困难。我应该写一个程序,让用户输入一个单词并输入要删除的字母,同时打印出其他字母。
这是我现在拥有的:
System.out.print("Please enter a word: ");
String word = kbreader.nextLine();
System.out.print("Enter the letter you want to remove: ");
for (int k = 0; k <= word.length(); k ++)
{
String remove = kbreader.nextLine();
String word2 = word.charAt(k) + "";
String remove2 = remove.charAt(0) + "";
if (!word2.equals(remove2))
{
System.out.print(word2);
}
}
这是一个示例:
输入一个字:aaabxaaa
输入要删除的字母:a
bx
答案 0 :(得分:3)
在Java中使用public String replace(char oldChar, char newChar)
函数。
修改为:
System.out.print("Please enter a word: ");
String word = kbreader.nextLine();
System.out.print("Enter the letter you want to remove: ");
String remove = kbreader.nextLine();
word = word.replace(remove ,"");
System.out.print(word);
答案 1 :(得分:2)
一种简单的处理方法是在此处使用String#replace
System.out.println(word.replace(remove, ""));
这将删除字符串remove
的所有实例,在您的情况下,它们只是一个字母。
执行此操作的另一种方法是迭代输入字符串,然后有选择地仅打印与要删除的字符不匹配的那些字符:
char charRemove = remove.charAt(0);
for (int i=0; i < s.length(); i++){
char c = s.charAt(i);
if (c != charRemove) System.out.print(c);
}
答案 2 :(得分:0)
这是您可以做到的方式:
System.out.print("Please enter a word: ");
String word = kbreader.nextLine();
System.out.print("Enter the letter you want to remove: ");
//read the char to remove just once before starting the loop
char remove = kbreader.nextLine().charAt(0);
for (int k = 0; k <= word.length(); k ++)
{
char word_char = word.charAt(k);
//check if the current char is equal to char required to be removed
if (word_char != remove)
{
System.out.print(word_char);
}
}