简体   繁体   English

删除字符串中的ASCII字符

[英]Removing ASCII Characters In A String

I am trying to remove the ASCII char(11) from the String. 我正在尝试从字符串中删除ASCII char(11)。 I can see the char(11) represents ' '. 我可以看到char(11)代表''。 However, when adding this as a String "' '" it turns out to be "''". 但是,将其添加为字符串“''”时,结果为“''”。

How can I check that the actual is a ASCII character ' '? 如何检查实际的ASCII字符是''?

The code is: 代码是:

public static void main(String[] args) {
    StringBuilder stringBuilder = new StringBuilder("' 'The name is stack");
    int value = 11;
    char data = (char) value; // in debug mode this is ' '
}

I want to delete this ASCII char if if exists at index 0. The problem is that the string is "''" instead of "' '". 如果索引0处存在该字符,我想删除此ASCII字符。问题是字符串是“”而不是“'”。 How can this be achived? 如何做到这一点?

I want the output to be The name is stack. 我希望输出为The name is stack。

You could do 你可以做

if (stringBuilder.charAt(0) == data) {
    stringBuilder.deleteCharAt(0);
}

I think the first "printable" character is the space symbol, at index 32. So drop anything below 32 and you should be fine. 我认为第一个“可打印”字符是索引为32的空格符号。因此,将所有内容都降到32以下,就可以了。 Should be trivial to extend to cover the whole string. 扩展到覆盖整个字符串应该是微不足道的。

You can assign characters as int values, and they correspond like shown here . 您可以指定字符为国际价值,以及它们对应像显示在这里

        char[] chars = new char[4];
        chars[0] = 31; // character for unit separator
        chars[1] = 65; // A
        chars[2] = 66; // B
        chars[3] = 67; // C

        // build a string from the printable and unprintable chars
        String s = new String(chars);

        // check length and how it prints out
        System.out.println("[" + s +"]");
        System.out.println(s.length());

        // if char at index 0 < 32, drop it
        if(s.charAt(0) < 32)
          s = s.substring(1, s.length());

        // prints like previously, but length is now smaller
        System.out.println("[" + s +"]");
        System.out.println(s.length());

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

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