📌  相关文章
📜  从字符串中替换所有换行符的Java程序

📅  最后修改于: 2022-05-13 01:54:36.035000             🧑  作者: Mango

从字符串中替换所有换行符的Java程序

换行符 (“\n”) 是单个字符,可以使用 replace()函数替换字符串中的所有换行符。

String replace():返回一个新的 String 对象,该对象包含与原始字符串相同的字符序列,但给定的字符被另一个给定的字符替换。

句法:

public String replace(char old,char new)

参数:

  • 旧:旧字符
  • 新:新字符

返回值:通过用新字符替换旧字符返回字符串

Java
// Java Program to Replace All Line Breaks from Strings
public class remove {
    public static void main(String[] args)
    {
        String s = "Replace\n"
                   + " all\n"
                   + " line\n"
                   + " breaks\n"
                   + " from\n"
                   + " strings";
        
        System.out.println(
            "Original String with line breaks:" + s);
        
        // replacing line breaks from string
        s = s.replace("\n", "");
        
        System.out.println(
            "String after replacing line breaks:" + s);
    }
}


输出
Original String with line breaks:Replace
 all
 line
 breaks
 from
 strings
String after replacing line breaks:Replace all line breaks from strings