Query about the trim() method in Java

前端 未结 2 973
孤城傲影
孤城傲影 2021-01-29 07:49

I asked a question earlier but met harsh criticism, so here I pose it again. Simpler, and rephrased to appeal to those who may have been concerned about the way I asked it befor

相关标签:
2条回答
  • 2021-01-29 07:56

    There must be a non-whitespace character in the source string. Add the following to your code and see what it prints.

    for (char ch : someString.toCharArray()) {
         System.out.print(Integer.toHexString(ch) + " ");
    }
    
    0 讨论(0)
  • 2021-01-29 08:16

    String.trim() specifically only removes characters before the first character whose code exceeds \u0020, and after the last such character.

    This is insufficient to remove all possible white space characters - Unicode defines several more (with code points above \u0020) that will not be matched by .trim().

    Perhaps your white space characters aren't the ones you think they are?

    EDIT comments revealed that the extra characters were indeed "special" whitespace characters, specifically \u00a0 which is a Unicode "non-breaking space". To replace those with normal spaces, use:

    str = str.replace('\u00a0', ' ');
    
    0 讨论(0)
提交回复
热议问题