Thursday, January 5, 2012

String Concatenation in Java


<< Previous Table of Categories Next >>


 
  /**
      * Feel free to copy and use this method
      * If you have any comments or better solutions, please paste on my blog: 
      * http://blog.yanmingyu.com or email me feedback.andrewyu@gmail.com 
      * 
      * Using "+" operator to cocat multiple Strings is convenient
      * but it is not efficient because String is immutable in Java.
      * We all know that we can use StringBuffer or StringBuilder to do this.
      * StringBuffer is synchronized and StringBuilder is not.
      * 
      * But creaging a StringBuffer or StringBuilder object every time
      * is boring when we need to concat strings. 
      * So it's more convenient to just call a function with variable-length argument
      * which is available from Java 5
      * 
      * A piece of testing source code is listed as the following:
      * 
      * String str1 = "StringA";
      * String str2 = "StringB";
      * String str3 = "StringC";
      * String result = concatStringByStringBuffer(str1, str2, str3);
      * or
      * String result = concatStringByStringBuilder(str1, str2, str3);
      */
    
    public static String concatStringByStringBuffer(String... strs)
    {
        if(strs==null)
        {
            return null;
        }
        StringBuffer stringBuffer = new StringBuffer();
        for (String s : strs)
        {
            stringBuffer.append(s); 
        }
        return stringBuffer.toString();
    }
    
    public static String concatStringByStringBuilder(String... strs)
    {
        if(strs==null)
        {
            return null;
        }
        StringBuilder stringBuilder = new StringBuilder();
        for (String s : strs)
        {
            stringBuilder.append(s); 
        }
        return stringBuilder.toString();
    }
  

No comments:

Post a Comment