简体   繁体   English

如何在Java中从回车符中修剪字符串

[英]How to trim a string from carriage returns in java

I have a string: 我有一个字符串:

\n\n\n\Mytext is here\n new line \n\n

with an unknown amount of \\n at the beginning and at the end. 在开始和结束时的\\ n数量未知。

How can I trim this string to 我怎么修剪这串

Mytext is here\n new line 

in an elegant way? 以优雅的方式?

I know I could code this with my own function. 我知道我可以使用自己的函数对此进行编码。 But, perhaps there is a simple solution? 但是,也许有一个简单的解决方案?

Trim it, using trim method of String which " Returns a copy of the string, with leading and trailing whitespace omitted. " 使用String trim方法修剪它,该方法“ 返回字符串的副本,并且省略前导和尾随空格。

Note that it Returns a copy of the string and doesn't edit the String 请注意,它返回字符串的副本,并且不编辑String

myString.trim()

Null Strings 空字符串

As @rmertins said, this is not "null safe", meaning if your String is null it will throw a NullPointerException so if your String can be null , wrap it. 正如@rmertins所说,这不是“空值安全”,这意味着如果您的Stringnull ,它将抛出NullPointerException因此如果您的String可以为null ,则将其包装起来。

if (myString != null)
{
  String newTrimmedString = myString.trim();
}

Importing an entire library to do this one task like @rmertins said (ie StringUtils from apache commons) is just overkill I'd say. 像@rmertins所说的那样,导入整个库来完成一项任务(例如,来自Apache Commons的StringUtils ),我会说是过头了。 I would also say it's bad practice to pass around null objects anyhow and null String objects suggests bad design. 我还要说,无论如何都要传递null对象是一个坏习惯,而null String对象则表明设计不好。

String.trim() will trim away white space at the beginning and end. String.trim()将在开头和结尾处String.trim()空白。 That would probably be the quickest way. 那可能是最快的方法。 If you need to retain other white spaces and only want to remove the \\n , I think you would have to replace them manually. 如果您需要保留其他空格而只想删除\\n ,我想您将不得不手动替换它们。

You could try something along the lines of 您可以尝试以下方法

myString = myString.replace("^(\\n)*","").replace("(\\n)*$","");

(I have not tried this code.) (我没有尝试过此代码。)

Check out the String.trim() method String.trim()方法

String foo = "\n\n  \n\t actual Value\t\n \n ";
System.out.println(foo.trim()); //prints "actual Value"

About as simple and elegant as it gets. 尽可能简单而优雅。 Keep in mind, though, that this will not only trim newline characters, but tabs, spaces, etc. as well. 但是请记住,这不仅会修剪换行符,还会修剪制表符,空格等。

如果您的字符串可能为null ,则可能要使用StringUtils.trim() - String.trim()的null安全版本。

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

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