【问题标题】:Java: how to take out a letter of a string while printing the rest of the letter in the stringJava:如何在打印字符串中其余字母的同时取出字符串中的一个字母
【发布时间】:2019-02-20 02:09:15
【问题描述】:

所以我几乎没有学习 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

【问题讨论】:

  • 您正在读取要在循环的每次迭代中删除的字符。这似乎是错误的。

标签: java string loops


【解决方案1】:

处理此问题的一种简单方法是在此处使用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】:

    在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);
    

    【讨论】:

      【解决方案3】:

      你可以这样做:

      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);
          }
      
      } 
      

      【讨论】:

      • 首先,您的答案没有“删除”部分。其次,它正在打印用户想要删除的字母。
      • @Jai 我的错,我想添加 != 并打错了字。我已经进行了编辑!
      猜你喜欢
      • 1970-01-01
      • 2021-04-20
      • 1970-01-01
      • 2022-12-20
      • 2019-07-16
      • 1970-01-01
      • 2016-07-17
      • 1970-01-01
      • 2021-05-11
      相关资源
      最近更新 更多