Each crlf is turned into an lf to deal with MSWindows, and then each remaining cr is turned into an lf to deal with Mac. - Java java.lang

Java examples for java.lang:String New Line

Description

Each crlf is turned into an lf to deal with MSWindows, and then each remaining cr is turned into an lf to deal with Mac.

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        String self = "java2s.com";
        System.out.println(canonical(self));
    }/* www  .  ja va2 s .  c o  m*/

    /**
     * Each crlf is turned into an lf to deal with MSWindows, and then each
     * remaining cr is turned into an lf to deal with Mac.
     */
    static public String canonical(String self) {
        if (-1 == self.indexOf('\r')) {
            return self;
        } else {
            return replaceAll(self, "\r\n", "\n").replace('\r', '\n');
        }
    }

    /**
     * The string-based replaceAll() supplements the character-based
     * replace().
     *
     * @see String#replace
     */
    static public String replaceAll(String self, String oldStr,
            String newStr) {
        StringBuffer buf = new StringBuffer(self.length() * 2);
        int oldLen = oldStr.length();
        int p1 = 0;
        for (int p2 = self.indexOf(oldStr); -1 != p2; p2 = self.indexOf(
                oldStr, p1)) {
            buf.append(self.substring(p1, p2));
            buf.append(newStr);
            p1 = p2 + oldLen;
        }
        buf.append(self.substring(p1));
        return buf.toString();
    }
}

Related Tutorials