简体   繁体   English

如何删除 java 中字符串末尾的空格?

[英]How to remove a white space at the end of a string in java?

I am trying to remove exactly one white space at the end of a string.我试图在字符串末尾删除一个空格。 eg.例如。 I want " XXXX " to be " XXXX".我希望“ XXXX”成为“ XXXX”。 The trim() method in java removes all leading and trailing whitespaces. java 中的 trim() 方法删除所有前导和尾随空格。

Any help will be appreciated:)任何帮助将不胜感激:)

If you just want to trim whitespace at the end, use String#replaceAll() with an appropriate regex:如果您只想在最后修剪空白,请使用String#replaceAll()和适当的正则表达式:

String input = " XXXX ";
String output = input.replaceAll("\\s+$", "");
System.out.println("***" + input + "***");   // *** XXXX ***
System.out.println("***" + output + "***");  // *** XXXX***

If you really want to replace just one whitespace character at the end, then replace on \s$ instead of \s+$ .如果您真的只想在末尾替换一个空格字符,请在\s$而不是\s+$上替换。

Since Java 11, String has a built-in method to to this: String.stripTrailing()自 Java 11 起, String对此有一个内置方法: String.stripTrailing()

It can be used like它可以像

String input = " XXX ";
String output = input.stripTrailing();

Note that, other than String.trim() , this method removes any whitespace at the end of the string, not just spaces.请注意,除了String.trim()之外,此方法会删除字符串末尾的所有空格,而不仅仅是空格。

try this solution:试试这个解决方案:

public String trim(String str) { 
 int len = str.length(); 
 int st = 0; 

 char[] val = str.toCharArray(); 

 while ((st < len) && (val[len - 1] <= ' ')) { 
  len--; 
 } 
 return str.substring(st, len); 
}

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

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