Monday, June 13, 2011

remove line break and carriage return from string java

Using String replaceAll

String s1 = "hello\r world \nhello world";
System.out.println(s1);
String s2 = s1.replaceAll("[\n\r]", "");
System.out.println(s2);


Here the first argument is replaced with the second argument.

First argument = regular expression used to specify what you want to replace
Second argument = string


I will show you a manual method to replace newline and carriage return from a string

Method 1:- Using two for loops , substring , indexOf , ternary operator

String s1 = "hello\r world \nhello world";

  String s2 ="";

  for(int j =0 ; j < 2 ; j++){
   
   for(int i = 0 ; i < s1.length() ; i++){

    if(s1.indexOf( j==0 ? '\n' : '\r' , i) != -1){
     s2 += s1.substring(i, s1.indexOf(j==0 ? '\n' : '\r', i));
     i = s1.indexOf(j==0 ? '\n' : '\r', i);
    }
    else{
     s2+=s1.substring(i, s1.length());
     break;
    }
   }

   if(j==0){
    s1 = s2;
    s2="";
   }
  }
  System.out.println(s2);


Method 2:- Using StringBuffer. This is a much cleaner method
StringBuffer stringBuffer = new StringBuffer();
  
  String s1 = "hello\r world \nhello world";
  
  for(int i = 0 ; i < s1.length() ; i++){
   
   if(s1.charAt(i) != '\n' && s1.charAt(i) != '\r' ){
    stringBuffer.append(s1.charAt(i));
   }
  }
  
  System.out.println(stringBuffer.toString());

No comments:

Post a Comment