简体   繁体   English

数字输入字符串“trim”和“replaceAll”不能去掉最后一个空格

[英]Digital type the string " trim " and " replaceAll " can't remove the last spaces

I want to remove all spaces in a string of numeric types, I used the function such as trim() , replaceall(" ", "") , but the last space always goes to off.我想删除数字类型字符串中的所有空格,我使用了诸如trim()replaceall(" ", "")类的函数,但最后一个空格总是关闭。

code:代码:

String str = " 13554912187 ";
//String str2 = str.replaceAll(" ", "");
String str2 = str.trim();
System.out.println(str);
System.out.println(str.length());
System.out.println(str2);
System.out.println(str2.length());

I want to know why.我想知道为什么。

Make sure the trailing space is actually considered whitespace by String.trim() - only characters with code less than or equal to \ are considered whitespace - see String.trim() documentation .确保尾随空格实际上被String.trim()视为空格 - 只有代码小于或等于\ 的字符才被视为空格 - 请参阅String.trim()文档

Some possible ways to check this:一些可能的方法来检查这个:

  • Copy the leading space and replace the trailing space with it (assuming the leading space works OK)复制前导空格并用它替换尾随空格(假设前导空格工作正常)
  • Open the file this input comes from in a hex editor在十六进制编辑器中打开此输入来自的文件
  • Debug the Java application and see what value is stored in the String instance for that last space调试 Java 应用程序并查看最后一个空间的String实例中存储了什么值
 String str = " 13554912187 ";

Trim leading and trailing blanks修剪前导和尾随空格

    str.trim(); -> "13554912187"

For left trim:对于左装饰:

    str.replaceAll("^\\s+", ""); -> "13554912187 "

For right trim:对于右修剪:

    str.replaceAll("\\s+$", ""); -> " 13554912187"

Visual proof for the incredulous怀疑者的视觉证据

视觉证明

String str2 = str.trim(); String str2 = str.trim();

trim() method remove space before and after the word. trim() 方法删除单词前后的空格。

like喜欢

String s=" 45654 65 ";
System.out.println(s.startsWith(" "));
System.out.println(s.endsWith(" "));

s=s.trim();
System.out.println(s.startsWith(" "));
System.out.println(s.endsWith(" "));

output:输出:

true
true
false
false

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

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