どうも、ちょげ(@chogetarou)です。
文字列(string)の改行を削除する方法を紹介します。
方法

文字列(string)の改行を削除するには、replace()を使います。
まず、文字列からreplace()を呼び出します。
そして、replace()の第1引数に「"\n"
」、第2引数に空文字を指定します。
String result = text.replace("\n", "");
上記のreplace()は、呼び出した文字列の改行を削除した文字列を返します。
もし、「\r
」も含めて削除する場合は、上記のreplace()からreplace()を呼び出します。
新しく呼び出したreplace()の第1引数に「"\r"
」、第2引数に空文字を指定します。
String result = text.replace("\n", "").replace("\r", "");
使用例
public class Main {
public static void main(String[] args) throws Exception {
String text = "\nHello,\n\nWorld\n";
String result = text.replace("\n", "");
System.out.println(result);
}
}
出力:
Hello,
World
コメント