【问题标题】:Remove characters from string builder从字符串生成器中删除字符
【发布时间】:2017-01-25 16:49:45
【问题描述】:

我正在尝试运行一个循环来从字符串中删除一些字符。但是当我运行以下代码时,我只能从第一次运行中获得输出(I on)。我没有得到其余的字符串。有人可以帮我在这里添加什么吗?仅显示第一次迭代的结果。谢谢

someStr = "I don't know this";
StringBuilder sb = new StringBuilder(someStr);
int n = 3
for (int i = n - 1; i < sb.length(); i = n + 1) {
    sb = sb.deleteCharAt(i);
}
System.out.println(sb.toString());

【问题讨论】:

  • 什么是n?...
  • 检查你的增量语句实际上在做什么
  • n 可以是任何整数,例如 2,3,4 等
  • 如果您编辑帖子以包含输入和预期输出,这将有助于我们解释您的逻辑错误是什么
  • “n 可以是任何整数”对任何人都没有用,它并不能说明您要达到的目标。

标签: java string stringbuilder


【解决方案1】:

for 语句的第三部分是增加或减少索引的指令。

那里,总是4。

为了更清楚:

1st iteration : i = 2 => you remove the 'd', your string is now "I on't know this"

2nd iteration : i = 4 => you remove the ''', your string is now "I ont know this"

3rd iteration : i = 4 => you remove the 't', your string is now "I on know this"

4th iteration : i = 4 => you remove the ' ', your string is now "I onknow this"

...

【讨论】:

    【解决方案2】:

    如果您想从字符串中删除字符,我建议您使用正则表达式。这是一个用空字符串替换您需要删除的字符的示例:

    public static String cleanWhitPattern(String sample, String , String regex) {
    
        if (sample != null && regex != null) {
            Pattern pattern = Pattern.compile(regex);
            Matcher matcher = pattern.matcher(sample);
    
            if (matcher.find()) {
                return matcher.replaceAll("");
            }
    
            return sample;
        }
    
        return null;
    }
    

    现在,您只需使用所需的模式调用此方法:

    System.out.print(cleanWithPattern("I don't know this", "o*"));
    

    你的输出应该是这样的:

    I dn't knw this

    【讨论】:

      【解决方案3】:

      为什么不使用 String.replaceAll()?

      someStr = "I don't know this";
      System.out.print("Output :" );
      System.out.println(someStr .replaceAll("t", ""));
      

      【讨论】:

      • 你能理解这个问题吗?它在 StringBuilder 类上,而不是在 String 类上。
      【解决方案4】:

      例如,如果您想从字符串中删除字符“k”,那么您可以执行以下操作

      JAVA:

      String someStr = "I don't know this";
      StringBuilder sb = new StringBuilder(someStr);
      
      if(sb.toString().contains("k")){
        int index = sb.indexOf("k");
        sb.deleteCharAt(index);
        System.out.println(sb.toString());
      }else{
        System.out.println("No such a char");
      }
      

      科特林:

      val someStr: String = "I don't know this"
      val sb: StringBuilder = StringBuilder(someStr)
      
      if(sb.toString().contains("k")){
        val index: Int = sb.indexOf("k")
        sb.deleteCharAt(index)
        print(sb.toString())
      
        }else{
         print("No such a char")
      }
      

      当然,您可以根据您想要的输出进行多种组合或多种改进。

      【讨论】:

        猜你喜欢
        • 2019-03-02
        • 1970-01-01
        • 1970-01-01
        • 2016-07-26
        • 2013-09-18
        • 2011-11-22
        相关资源
        最近更新 更多