Re: string comparison with null
RedGrittyBrick wrote :
Lew wrote:
focode wrote:
String str = null;
int value = textFIeldString.compareTo(str);
but this throws exception
rossum wrote:
To test for null use:
if (textFIeldString == null) { ... }
to test for zero length I tend to use:
if (textFIeldString.length() == 0) { ... }
To test for empty, combine those two:
( text == null || text.length() == 0 )
( text == null || text.trim().length() == 0 )
Next ...
I wrote a small method which left-justifies text. The idea being that
any text only has one space between words. This is useful in doing
searches because you know that all user input is correctly and
identically formatted. And it looks good on printouts.
-------------------------------------
text = Convert.leftJustify(text);
if ( text.length() == 0 )
-------------------------------------
And just because I am a nice guy (be gentle...):
-------------------------------------
/**
* This method formats a String. <br>
* <br>
* It places the first non-white space character at the left, and
removes all extra spaces. <br>
* So " a bc cd" will be returned as
"a bc cd"
*/
public static String leftJustify( String theValue )
{
char charArray[];
try
{
charArray = theValue.toCharArray();
}
catch (NullPointerException e)
{
return "";
}
StringBuffer out = new StringBuffer( charArray.length + 1 );
// remove any leading whitespace
boolean isSpace = true;
for (int c = 0; c < charArray.length; c++)
{
// leave CRLF for multiline inputs
if (!(charArray[c] == '\n' || charArray[c] == '\r') &&
Character.isWhitespace( charArray[c] ))
{
if (!isSpace)
out.append( ' ' );
isSpace = true;
}
else
{
out.append( charArray[c] );
isSpace = false;
}
}
// remove trailing space
if (isSpace && out.length() > 0)
{
String justified = out.toString();
return justified.substring( 0, justified.length() - 1 );
}
return out.toString();
}
-------------------------------------
Test:
System.out.println("'" +
ca.rcmp.esi.utility.tools.Convert.leftJustify(null) + "'");
System.out.println("'" +
ca.rcmp.esi.utility.tools.Convert.leftJustify("") + "'");
System.out.println("'" +
ca.rcmp.esi.utility.tools.Convert.leftJustify(" ") + "'");
System.out.println("'" +
ca.rcmp.esi.utility.tools.Convert.leftJustify(" b c e ") + "'");
System.out.println("'" +
ca.rcmp.esi.utility.tools.Convert.leftJustify("b c e") + "'");
Result:
''
''
''
'b c e'
'b c e'
--
Wojtek :-)