views:

49

answers:

2

Problem: If String ends with \r, remove \r

I started with something like this

if (masterValue.endsWith(CARRIAGE_RETURN_STR)) {
  masterValue = masterValue.replace(CARRIAGE_RETURN_STR, "");
}

where

public static final String CARRIAGE_RETURN_STR = (Character.toString(Constants.CARRIAGE_RETURN));
public static final char CARRIAGE_RETURN = '\r';

This seems awkward to me.

Is there an easy way to just remove \r character?

I then moved on to this:

if (value.contains(CARRIAGE_RETURN_STR)) {
   value = value.substring(0, value.length()-3);

//-3 because we start with 0 (1), line ends with \n (2) and we need to rmove 1 char (3)

But this too seems awkward .

Can you suggest a easier, more elegant solution?

+6  A: 

Regexes can support end-of-string anchoring, you know. (See this Javadoc page for more information)

myString.replaceAll("\r$", "");

This also takes care of fixing \r\n --> \n, I believe.

Platinum Azure
+1  A: 

I'd write it like this:

if (masterValue.endsWith("\r")) {
    masterValue = masterValue.substring(0, masterValue.length() - 1);
}

I see no point in creating a named constant for the String "\r".

By the way, your second attempt is incorrect because:

  1. String.contains("\r") tells you if the String contains a carriage return, not if it ends with a carriage return,
  2. the second argument of String.substring(int, int) is the index of the end character; i.e. the position first character that should NOT be in the substring, and
  3. the length of "\r" is one.
Stephen C