简体   繁体   English

代替 ! Java中的空字符

[英]Replace ! with an empty character in Java

With the given input test!! test!!! test !!!使用给定的输入test!! test!!! test !!! test!! test!!! test !!! the program below should return test! test! test !下面的程序应该返回test! test! test ! test! test! test ! by removing all but one of '!'通过删除除一个“!”之外的所有内容or '?'或者 '?' in a row.连续。

However the program outputs it like this: test! test! test ! !然而程序输出它是这样的: test! test! test ! ! test! test! test ! !

How would I remove the extra '!'我将如何删除多余的“!” or '?'或者 '?' characters?人物?

StringBuilder sb = new StringBuilder(input);

for (int i = 0; i < input.length() - 1; i++)
{   
    // Does string contain '?' or '!'
    if (input.charAt(i) == '?' || input.charAt(i) == '!') {
        // TODO: Remove extra characters
    }
    else
    {
         sb.setCharAt(i, input[i]);
    }
}

System.out.println(sb.toString());

Hints:提示:

  1. There is no such thing as an empty character.没有空字符这样的东西。 So sb.setCharAt(i, empty);所以sb.setCharAt(i, empty); is actually replacing the character at position i with a NON-EMPTY character.实际上是用非空字符替换位置i处的字符。 It looks like its is a space character;看起来它是一个空格字符; ie Unicode / ASCII SP .即 Unicode / ASCII SP

  2. You can use deleteCharAt(1) to remove a character at position i of a StringBuilder .您可以使用deleteCharAt(1)删除StringBuilder位置i处的字符。 But beware that removing the character at position i causes the characters at i + 1 , i + 2 and so on to change position .但请注意,删除位置i处的字符会导致i + 1i + 2等处的字符更改位置 You need to take account of that in your code.您需要在代码中考虑到这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM