/*
* Copyright © 2013 - Elliott Frisch
*
* THIS SOFTWARE IS PROVIDED UNDER THE CREATIVE COMMONS
* LICENSE 3.0 "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR
* A PARTICULAR PURPOSE.
*
* To use this software you must agree to the complete
* license terms available at:
* http://creativecommons.org/licenses/by/3.0/us/deed.en_US
*
* It is the intent of the author(s) that you may use or
* modify this software for any purpose (including your own
* commercial gain) provided that this notice remains in its
* entirety.
*
* Created by Elliott Frisch - www.frischcode.com
*/
package com.frischcode.util;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
* <b>Rationale:</b> Frequently used methods for safely
* trimming String(s) and guarding against null.
*
* @author Elliott Frisch
*/
public class SafeString {
/**
* Safely trim a String. Will help guard against null(s).
*
* @param in
* The String to trim.
* @return The trimmed String if <b>in</b> is not null,
* otherwise the empty String.
*/
public static String safeTrim(final String in) {
return (in != null) ? in.trim() : "";
}
/**
* Safely trim an Array of String(s). Will ensure that
* every String is trimmed or empty. <b>NOTE:</b> Will
* return an EMPTY String Array on null in.
*
* @param in
* The String(s) to trim.
* @return The trimmed String(s).
*/
public static String[] safeTrim(final String... in) {
if (in == null) {
return new String[] {};
}
if (in.length > 0) {
for (int i = 0; i < in.length; ++i) {
in[i] = safeTrim(in[i]);
}
}
return in;
}
/**
* Safely trim a Collection of String(s). Will ensure that
* every String is trimmed or empty. <b>NOTE:</b> Will
* return an EMPTY String Collection on null in.
*
* @param in
* The Collection of String(s) to trim.
* @return The trimmed String(s).
*/
public static Collection<String> safeTrim(
final Collection<String> in) {
final List<String> al = new ArrayList<String>();
if (in == null) {
return al;
}
if (in.size() > 0) {
for (final String str : in) {
al.add(safeTrim(str));
}
in.clear();
in.addAll(al);
}
return in;
}
}
Code Pretty Print Script
Sunday, November 10, 2013
Safely Handling Strings
Dealing with a lot of Strings? Leading and trailing white space got you down? Wish there was a consistently easy approach to ensure that they're all trimmed and to guard against null?
Subscribe to:
Post Comments
(
Atom
)
No comments :
Post a Comment