从字符串构建器中删除字符

时间:2017-01-25 16:49:45

标签: java string stringbuilder

我试图运行一个循环来从字符串中删除一些字符。但是当我运行以下代码时,我只能从第一次运行中获得输出(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());

4 个答案:

答案 0 :(得分: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"

...

答案 1 :(得分:1)

如果要从字符串中删除字符,我建议您使用Regex。这是用空字符串替换您需要删除的字符的示例:

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

答案 2 :(得分:0)

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

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

答案 3 :(得分:0)

例如,如果要从字符串中删除字符“ 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")
}

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