Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
Creative commons Attribution-NonCommercial license. http://creativecommons.org/licenses/by-nc/2.5/au/deed.en_GB NO WARRANTY IS GIVEN OR IMPLIED, USE AT YOUR OWN RISK.
 
 package base.email.encoding;
 
public class PlainTextEncoding extends Encoding{

Remove CR and LF characters from the start and end of a string.

Parameters:
line String to trim
Returns:
String with all CR and LF's removed from the start and end
	private String trimCrlf(String line) {
		while(line.endsWith("\n") || line.endsWith("\r")) {
			line = line.substring(0, line.length()-1);
		}
		while(line.startsWith("\n") || line.startsWith("\r")) {
			line = line.substring(1, line.length()-1);
		}
		return line;
	}

Ensure all lines consistently end with CRLF, and ensure the full stop (period) character is escaped properly.
	public String encode(String message) {
		if(message == null || message == "") {
			return message;
		}
		int crlfCount = countSubstring(message"\r\n");
		int crCount = countSubstring(message"\r");
		int lfCount = countSubstring(message"\n");
		String splitBy = "\n";
		if(crlfCount > crCount && crlfCount > lfCount) {
			splitBy = "\r\n";
		}
		if(crCount > crlfCount && crCount > lfCount) {
			splitBy = "\r";
		}
		if(lfCount > crCount && lfCount > crlfCount) {
			splitBy = "\n";
		}
		StringBuffer result = new StringBuffer();
		for(String line : message.split(splitBy)) {
			line = trimCrlf(line);
			if(line.matches("^\\.+$")) {
				line = line + ".";
			}
			result.append(line);
			result.append("\r\n");
		}
		return result.toString();
	}
New to GrepCode? Check out our FAQ X