10 Simple String Utility Methods for Java Developer

String operations are common to all kind of programming. Java has many in built operations supported by String class. There are few functions which I observed commonly used and may be helpful to keep handy as StringUtil class with static methods.

  1. Getting Exception Stack Trace to String value
  2. Exceptions class provides a printStackTrace() method which directly prints the Stack Trace to the console. Sometimes you may need to take stack trace to a String variable and use it (e.g. logging using logger), or doing processing on the trace e.g. eclipse shows stack trace and links it to the file and line number. Below is a simple piece of code which demonstrates how we can capture the stack trace inside as String variable. This example utilizes the StringWriter class to convert the stream content to a String.
    public static String toString(Exception e) {
    
        StringWriter s = new StringWriter();
        e.printStackTrace(new PrintWriter(s));
        return s.toString(); 
    }
    
  3. Merging two String arrays

  4. This is another simple Java String utility method, which can be used to merge two arrays of String values. This takes care of eliminating the duplicates and also does null checking. If you are dealing with multiple String arrays then it could be a useful method.
     /**
      * This String utility or util method can be used to merge 2 arrays of
      * string values. If the input arrays are like this array1 = {"a", "b" ,
      * "c"} array2 = {"c", "d", "e"} Then the output array will have {"a", "b" ,
      * "c", "d", "e"}
      * 
      * This takes care of eliminating duplicates and checks null values.
      * 
      * @param values
      * @return
      */
     public static String[] mergeStringArrays(String array1[], String array2[]) {
     
      if (array1 == null || array1.length == 0)
       return array2;
      if (array2 == null || array2.length == 0)
       return array1;
      List array1List = Arrays.asList(array1);
      List array2List = Arrays.asList(array2);
      List result = new ArrayList(array1List);  
      List tmp = new ArrayList(array1List);
      tmp.retainAll(array2List);
      result.removeAll(tmp);
      result.addAll(array2List);  
      return ((String[]) result.toArray(new String[result.size()]));
     }
    

  5. Trim List of String
  6. This is a Collections List equivalent of the trim method for String Array. This can be used to trim all String values in a List of Strings. It takes care of null checking.
    /**
     * This String utility or util method can be used to trim all the String
     * values in list of Strings. For input [" a1 ", "b1 ", " c1"] the output
     * will be {"a1", "b1", "c1"} Method takes care of null values. This method
     * is collections equivalent of the trim method for String array.
     *
     * @param values
     * @return
     */
    public static List trim(final List values) {
    
     List newValues = new ArrayList();
     for (int i = 0, length = values.size(); i < length; i++) {
      String v = (String) values.get(i);
      if (v != null) {
       v = v.trim();
      }
      newValues.add(v);
     }
     return newValues;
    }
    

  7. Trim array of String
  8. This is another simple but useful Java String Utility/Util method, which can be used to trim all String values in an array of String. This takes care of null checking while doing trim. java.lang.String class contains the trim method which can be used to trim a string from left and right both sides. So for example if you have a string [" This is a String "] then calling a trim() method on this string will convert it to ["This is a String"].
    /**
     * This String utility or util method can be used to
     * trim all the String values in the string array.
     * For input {" a1 ", "b1 ", " c1"}
     * the output will be {"a1", "b1", "c1"}
     * Method takes care of null values.
     * @param values
     * @return
     */
    public static String[] trim(final String[] values) {
    
     for (int i = 0, length = values.length; i < length; i++) {
      if (values[i] != null) {
       values[i] = values[i].trim();                                
      }
     }
     return values;
    
    }
    

  9. Unquoting the String
  10. This method can be used to unquote a string value. This method takes care of single and double quotes both along with handling the null string. It returns the string as it is when the string is not quoted.
    /**
     * This String util method removes single or double quotes
     * from a string if its quoted.
     * for input string = "mystr1" output will be = mystr1
     * for input string = 'mystr2' output will be = mystr2
     *
     * @param String value to be unquoted.
     * @return value unquoted, null if input is null.
     *
     */
    public static String unquote(String s) {
    
     if (s != null
       && ((s.startsWith("\"") && s.endsWith("\""))
       || (s.startsWith("'") && s.endsWith("'")))) {
    
      s = s.substring(1, s.length() - 1);
     }
     return s;
    }
    /**
     * Same method as above but using the ?: syntax which is shorter. You can use whichever you prefer.
     * This String util method removes single or double quotes from a string if
     * its quoted. for input string = "mystr1" output will be = mystr1 for input
     *  
     * string = 'mystr2' output will be = mystr2
     *
     * @param String
     *            value to be unquoted.
     * @return value unquoted, null if input is null.
     *
     */
    public static String unquote2(String s) {
    
     return (s != null && ((s.startsWith("\"") && s.endsWith("\"")) || (s
       .startsWith("'") && s.endsWith("'")))) ? s = s.substring(1, s
       .length() - 1) : s;
    
    } 
    

  11. Extracting File Name from Absolute path
  12. Exact file name extraction is required many times, when dealing with files. Below is a String utility method, which can be used to extract the exact file name from a absolute path. It uses the File.separatorChar which should take care of all platforms.
    /**
    * This method extracts the file name from absolute path of file
    * As an example :
    * 
    * *
    * For an input "c:\myDir\MyFile.java"
    * The output will be : "MyFile"
    * 
    * *
    * * @param absoluteFileName File name with path * @return FileName minus the path */ public static String extractFileName(String absoluteFileName) { if (!isNullOrEmpty(absoluteFileName)) { absoluteFileName = absoluteFileName.substring(absoluteFileName .lastIndexOf(File.separatorChar) + 1, absoluteFileName.lastIndexOf(".")); } return absoluteFileName; }

  13. Getting Array/List of tokens from String
  14. This method can be used to convert a String separated by delimiter into an array of String.
    /**
    * This method is used to split the given string into different tokens at
    * the occurrence of specified delimiter
    * An example :
    * "abcdzefghizlmnop" and using a delimiter "z"
    * would give following output
    * "abcd" "efghi" "lmnop"
    *
    * @param str The string that needs to be broken
    * @param delimeter The delimiter used to break the string
    * @return a string array
    */
    
    public static String[] getTokensArray(String str, String delimeter) {
    
    String[] data;
    if(str == null){
        return null;
    }
    
    if (delimeter == null || "".equals(delimeter)
    || "".equals(str)) {
        data = new String[1];
        data[0] = str;
        return data;
    } else {
        StringTokenizer st = new StringTokenizer(str, delimeter);
        int tokenCount = st.countTokens();
        data = new String[tokenCount];
        for (int i = 0; st.hasMoreTokens(); i++) {
        data[i] = st.nextToken();
    }
    return data;
    }
    }
    
    A better and simpler/improved version of same method is suggested by one of readers and the code looks like this.
    /**
    * This method is used to split the given string into different tokens at
    * the occurrence of specified delimiter
    * An example :
    * "abcdzefghizlmnop" and using a delimiter "z"
    * would give following output
    * "abcd" "efghi" "lmnop"
    *
    * @param str The string that needs to be broken
    * @param delimeter The delimiter used to break the string
    * @return a string array
    */
     public static String[] getTokensArray(String str, String delimeter) {
      if (str != null) {
       return str.split(delimeter);
      }
      return null;
     }
    
    Another variation for same method is for getting a java.util.List instead of array of objects. This can be easily done using small change to above method
    /**
    * This method is used to split the given string into different tokens at
    * the occurrence of specified delimiter
    * An example :
    * "abcdzefghizlmnop" and using a delimiter "z"
    * would give following output
    * "abcd" "efghi" "lmnop"
    *
    * @param str The string that needs to be broken
    * @param delimeter The delimiter used to break the string
    * @return a instance of java.util.List with each token as one item in list
    */
    
     public static List getTokensList(String str, String delimeter) {
      if (str != null) {
       return Arrays.asList(str.split(delimeter));
      }
      return new ArrayList();
     }
    
    

  15. Checking Starts/Ends with Ignoring the case
  16. The java.lang.String class default implementation has startsWith and endsWith() methods which perform case sensitive comparison, Below are two functions, which can be used to do the same startsWith/endsWith check ignoring the case.
    /**
    * Check a String ends with another string ignoring the case.
    *
    * @param str
    * @param suffix
    * @return
    */
    public static boolean endsWithIgnoreCase(String str, String suffix) {
    
        if (str == null || suffix == null) {
            return false;
        }
        if (str.endsWith(suffix)) {
            return true;
        }
        if (str.length() < suffix.length()) {
            return false;
        } else {
            return str.toLowerCase().endsWith(suffix.toLowerCase());
        }
    }
    
    /**
    * Check a String starts with another string ignoring the case.
    *
    * @param str
    * @param prefix
    * @return
    */
    
    public static boolean startsWithIgnoreCase(String str, String prefix) {
    
        if (str == null || prefix == null) {
            return false;
        }
        if (str.startsWith(prefix)) {
            return true;
        }
        if (str.length() < prefix.length()) {
            return false;
        } else {
            return str.toLowerCase().startsWith(prefix.toLowerCase());
        }
    }
    

  17. Converting String to set of Unique tokens
  18. This method can be used to create a set of unique string values from a string which has tokens separated by some separator. This is very useful method when you get the input as comma or space separated string, which has to be converted to set of values when dealing with each value individually and avoiding duplicates. The code is using StringTokenizer for separating the tokens, so single or multiple separators can be used.
    /**
    * This method creates a set of unique string tokens which are separated by
    * separator
    *
    * @param str
    * @param separator
    * @return
    */
    public static Set getUniqueTokens(String str, String separator) {
    
     StringTokenizer tokenizer = new StringTokenizer(str, separator);
     Set tokens = new HashSet();
     while (tokenizer.hasMoreTokens()) {
         tokens.add(tokenizer.nextToken());
     }
     return tokens;
    }
    
    Another way of writing the same method is (suggested by a reader in comments section) is using the String.split() method. Below is the code for same
    /**
    * This method creates a set of unique string tokens which are separated by
    * separator
    *
    * @param str
    * @param separator
    * @return
    */
    public static Set getUniqueTokens(String str, String separator) {
     String [] tmpStr = str.split(separator);
     return new HashSet(Arrays.asList(tmpStr));
    }
    

  19. Masking Null String value
  20. There are times when we don't want to deal with null String values, in such cases below utility method can be utilized. This method return a empty string value in case the string value is null. Same argument of extra method call may come up for this as well, but you may save unwanted NullPointerException in your application by using such a method. I have found this useful at places where we are displaying a field value on user interface and want to mask the null values with empty string.
    /**
    * Return a not null string.
    *
    * @param s String
    * @return empty string if it is null otherwise the string passed in as
    * parameter.
    */
    
    public static String nonNull(String s) {
    
    if (s == null) {
        return "";
    }
    return s;
    }
    
Can you think of a function which is not part of this list? Please don't forget to share it with me in comments section & I will try to include it in the list.

Related

Example Code 1245252241047438844

Post a Comment Default Comments

  1. Great list Sachin

    ReplyDelete
  2. a lot of these may be in commons lang framework

    ReplyDelete
  3. True, Just in case you don't want to use the commons library, you may keep a lightweight utility class.

    ReplyDelete
  4. Good Collection..!! Thanks for sharing..!
    -Vamsi

    ReplyDelete
  5. hey any one tell pls. Is there any methods available for util.. pl pl

    ReplyDelete
  6. for me also same doubt ya...

    ReplyDelete
  7. @Priya & @Vino - I am not sure if I understand your question? What method are you looking for?

    ReplyDelete
  8. Instead of your implementation how about the below.

    public static Set getUniqueTokens(String str, String separator) {
    String [] tmpStr = str.split(separator);
    return new HashSet(Arrays.asList(tmpStr));
    }

    ReplyDelete
  9. @Anonymous - Thanks for the suggestion, I will add this as another option for same method to choose from. Thanks for sharing this piece of code. Do you have some insight on the performance of String.split() vs StringTokenizer, I guess StringTokenizer has an edge on perf but split is not too bad either.

    ReplyDelete
  10. thank u it is very good site for java developers

    ReplyDelete
  11. Is #6 required?

    import java.io.File;

    public final class FileName {
    public static final void main(final String[] args) {
    final String strFileName = "c:/myDir/MyFile.java";
    final File file = new File(strFileName);
    System.out.println("FileName==>" + file.getName());
    }
    }

    ReplyDelete
  12. @P7h - thanks for your comment. Your version is much better. I will update my code.

    ReplyDelete
  13. // Don't create lots of empty string objects
    private final static String emptyString = "";

    public static String nonNull(String s) {
    if (s == null) {
    return emptyString;
    }
    return s;
    }

    ReplyDelete

Individuals who comment on FromDev at regular basis, will be rewarded in Top Commenter section. (Comments are selectively moderated so please do not spam)

emo-but-icon

item