Java String Remove Carriage Return

Java String Remove Carriage Return | In this section, we will discuss the carriage return in Java. It is a special character where it brings the cursor to the starting of line without making any changes to the line. This is commonly abbreviated as CR and its ASCII value is 13 or 0x0D. We can denote the carriage return as ‘\r’.

See the below example of the special character ‘\r’ carriage return.
String = “Hi This is Java\r Program”.
String = “Hello\r kitty!”.

public class Main {
   public static void main(String[] args) throws Exception {
      String str = "One\rTwo";
      System.out.println(str);
      System.out.print("Hello healthy \rWorld");
   }
}

Output:-

One
Two
Hello healthy
World

The problem statement here is to remove the carriage return ‘\r’ from the string to do that we can use the replaceAll() method. The repaceAll() method replaces all the occurrences of the substring with the given substring.

Java Remove Carriage Return From String

In this code, we have taken a string called str which has the carriage return ‘\r’ character, and also we have a print statement containing the carriage return character. We can see the difference between both. After removing the carriage return character ‘\r’ in the first string, the string is printed as it and also we have not removed the carriage return in the print statement so that we can observe the difference. 

public class Main {
   public static void main(String[] args) throws Exception {
      String str = "One\rTwo";
      System.out.println(str);
      String str1 = str.replaceAll("\r", " ");
      System.out.println(str1);
   }
}

Output:-

One
Two
One Two

Java Program To Remove Carriage Return Character From The String

Let us see another Java program to remove carriage return character from the string.

public class Main {
   public static void main(String[] args) {

      String str1 = "I am going to Market\rS ";
      String str2 = "Hello healthy \rWorld";
      System.out.println(str1);
      System.out.println(str2);

      str1 = str1.replaceAll("\r", " ");
      str2 = str2.replaceAll("\r", " ");
      System.out.println(str1);
      System.out.println(str2);
   }
}

Output:-

I am going to Market
S
Hello healthy
World
I am going to Market S
Hello healthy World

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *