Find and replace all NewLine or BreakLine characters with \n in a String - Platform independent

后端 未结 3 1669
深忆病人
深忆病人 2020-12-09 19:58

I am looking for a proper and robust way to find and replace all newline or breakline chars from a String independent of any OS platfo

3条回答
  •  一个人的身影
    2020-12-09 20:16

    Oh sure, you could do it with one line of regex, but what fun is that?

    public static String fixToNewline(String orig){
        char[] chars = orig.toCharArray();
        StringBuilder sb = new StringBuilder(100);
        for(char c : chars){
            switch(c){
                case '\r':
                case '\f':
                    break;
                case '\n':
                    sb.append("\\n");
                    break;
                default:
                    sb.append(c);
            }
        }
        return sb.toString();
    }
    
    public static void main(String[] args){
       String s = "This is \r\n a String with \n Different Newlines \f and other things.";
    
       System.out.println(s);
       System.out.println();
       System.out.println("Now calling fixToNewline....");
       System.out.println(fixToNewline(s));
    
    }
    

    The result

    This is 
     a String with 
     Different Newlines  and other things.
    
    Now calling fixToNewline....
    This is \n a String with \n Different Newlines  and other things.
    

提交回复
热议问题