* Removes spaces (char <= 32) from both start and ends of this bytes
* array, handling null by returning null.
*
* StringUtils.trim(null) = null
* StringUtils.trim("") = ""
* StringUtils.trim(" ") = ""
* StringUtils.trim("abc") = "abc"
* StringUtils.trim(" abc ") = "abc"
*
*
* @param bytes the byte array to be trimmed, may be null
*
* @return the trimmed byte array
*/
public static final byte[] trim( byte[] bytes )
{
if ( isEmpty( bytes ) )
{
return new byte[0];
}
int start = trimLeft( bytes, 0 );
int end = trimRight( bytes, bytes.length - 1 );
int length = end - start + 1;
if ( length != 0 )
{
byte[] newBytes = new byte[end - start + 1];
System.arraycopy( bytes, start, newBytes, 0, length );
return newBytes;
}
else
{
return new byte[0];
}
}
/**
*
* Removes spaces (char <= 32) from start of this array, handling
* null by returning null.
*
* StringUtils.trimLeft(null) = null
* StringUtils.trimLeft("") = ""
* StringUtils.trimLeft(" ") = ""
* StringUtils.trimLeft("abc") = "abc"
* StringUtils.trimLeft(" abc ") = "abc "
*
*
* @param bytes
* the byte array to be trimmed, may be null
* @return the position of the first byte which is not a space, or the last
* position of the array.
*/
public static final int trimLeft( byte[] bytes, int pos )
{
if ( bytes == null )
{
return pos;
}
while ( ( pos < bytes.length ) && ( bytes[pos] == ' ' ) )
{
pos++;
}
return pos;
}
/**
*
* Removes spaces (char <= 32) from end of this array, handling
* null by returning null.
*
* StringUtils.trimRight(null) = null
* StringUtils.trimRight("") = ""
* StringUtils.trimRight(" ") = ""
* StringUtils.trimRight("abc") = "abc"
* StringUtils.trimRight(" abc ") = " abc"
*
*
* @param bytes
* the chars array to be trimmed, may be null
* @return the position of the first char which is not a space, or the last
* position of the array.
*/
public static final int trimRight( byte[] bytes, int pos )
{
if ( bytes == null )
{
return pos;
}
while ( ( pos >= 0 ) && ( bytes[pos] == ' ' ) )
{
pos--;
}
return pos;
}
/**
* Checks if a bytes array is empty or null.
*
* @param bytes
* The bytes array to check, may be null
* @return true if the bytes array is empty or null
*/
public static final boolean isEmpty( byte[] bytes )
{
return bytes == null || bytes.length == 0;
}
}