删除字符串中的换行符号的几种方式:
1.使用String的replaceAll()方法;
2.使用google guava的CharMatcher.breakingWhitespace();
3.使用Apache Commons包的StringUtils.chomp();方法;
pom依赖
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>25.1-jre</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.7</version>
</dependency>
代码
package com.example.demo;
import com.google.common.base.CharMatcher;
import org.apache.commons.lang3.StringUtils;
/**
* @author Walker
* @since 1.0 2018-10-09
*/
public class RemoveCarriageTest {
public static void main(String[] args) {
//使用replaceAll
String text = "Our line rackets \rthe encouraged symmetry.\n";
String result = text.replaceAll("\n", "").replaceAll("\r", "");
System.out.println(result);
String randomSentence = "The backed valley manufactures \r"
+ "a politician above \n" + "a scratched body.";
//google guava
result = CharMatcher.breakingWhitespace().removeFrom(randomSentence);
System.out.println(result);
//apache commons
String randomSentence2 = "The pocket reflects "
+ "over an intimate. \r";
result = StringUtils.chomp(randomSentence2);
System.out.println(result);
}
}
结果
Our line rackets the encouraged symmetry.
Thebackedvalleymanufacturesapoliticianaboveascratchedbody.
The pocket reflects over an intimate.