Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Licensed to the Apache Software Foundation (ASF) under one
   * or more contributor license agreements.  See the NOTICE file
   * distributed with this work for additional information
   * regarding copyright ownership.  The ASF licenses this file
   * to you under the Apache License, Version 2.0 (the
   * "License"); you may not use this file except in compliance
   * with the License.  You may obtain a copy of the License at
   *
  *   http://www.apache.org/licenses/LICENSE-2.0
  *
  * Unless required by applicable law or agreed to in writing,
  * software distributed under the License is distributed on an
  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  * KIND, either express or implied.  See the License for the
  * specific language governing permissions and limitations
  * under the License.
  */
 package org.apache.myfaces.shared.util;
 
Implements utility functions for the String class

Emphasis on performance and reduced memory allocation/garbage collection in exchange for longer more complex code.

Author(s):
Anton Koinov (latest modification by $Author: lu4242 $)
Version:
$Revision: 1215303 $ $Date: 2011-12-16 16:46:52 -0500 (Fri, 16 Dec 2011) $
 
 public final class StringUtils
 {
     private StringUtils()
     {
         // utility class, no instantiation
     }
 
     //~ Methods ------------------------------------------------------------------------------------
 
    
Checks that the string represents a floating point number that CANNOT be in exponential notation

Parameters:
str the string to check
Returns:
boolean
 
     public static boolean isFloatNoExponent(String str)
     {
         int len = str.length();
         if (len == 0)
         {
             return false;
         }
 
         // skip first char if sign char
         char c = str.charAt(0);
         int  i = ((c == '-') || (c == '+')) ? 1 : 0;
 
         // is it only a sign?
         if (i >= len)
         {
             return false;
         }
 
         boolean decimalPointFound = false;
 
         do
         {
             c = str.charAt(i);
             if (c == '.')
             {
                 // is this a second dot?
                 if (decimalPointFound)
                 {
                     return false;
                 }
 
                 decimalPointFound = true;
             }
             else if (!Character.isDigit(c))
             {
                 return false;
             }
 
             i++;
         }
         while (i < len);
 
         return true;
     }
 
     public static boolean isFloatWithOptionalExponent(String str)
     {
         int len = str.length();
        if (len == 0)
        {
            return false;
        }
        // skip first char if sign char
        char c = str.charAt(0);
        int  i = ((c == '-') || (c == '+')) ? 1 : 0;
        // is it only a sign?
        if (i >= len)
        {
            return false;
        }
        boolean exponentFound     = false;
        boolean decimalPointFound = false;
        do
        {
            c = str.charAt(i);
            switch (c)
            {
                case '.':
                    // is this a second one, are we in the exponent?
                    if (decimalPointFound || exponentFound)
                    {
                        return false;
                    }
                    decimalPointFound = true;
                    break;
                case 'e':
                case 'E':
                    // is this a second one?
                    if (exponentFound)
                    {
                        return false;
                    }
                    exponentFound = true;
                    // check for exponent sign
                    c = str.charAt(i + 1);
                    if ((c == '-') || (c == '+'))
                    {
                        i++;
                    }
                    break;
                default:
                    if (!Character.isDigit(c))
                    {
                        return false;
                    }
            }
            i++;
        }
        while (i < len);
        return true;
    }
    public static boolean isInteger(String str)
    {
        int len = str.length();
        if (len == 0)
        {
            return false;
        }
        // skip first char if sign char
        char c = str.charAt(0);
        int  i = ((c == '-') || (c == '+')) ? 1 : 0;
        // is it only a sign?
        if (i >= len)
        {
            return false;
        }
        do
        {
            if (!Character.isDigit(str.charAt(i)))
            {
                return false;
            }
            i++;
        }
        while (i < len);
        return true;
    }
    public static boolean isUnsignedInteger(String str)
    {
        int len = str.length();
        if (len == 0)
        {
            return false;
        }
        for (int i = 0; i < leni++)
        {
            if (!Character.isDigit(str.charAt(i)))
            {
                return false;
            }
        }
        return true;
    }

    
Undoubles the quotes inside the string
Example:
 hello""world becomes hello"world
 

Parameters:
str input string to dequote
quote the quoting char
Returns:
dequoted string
    public static String dequote(String strchar quote)
    {
        // Is there anything to dequote?
        if (str == null)
        {
            return null;
        }
        return dequote(str, 0, str.length(), quote);
    }

    
Undoubles the quotes inside a substring
Example:
 hello""world becomes hello"world
 
WARNING: scan for quote may continue to the end of the string, make sure that either charAt(end + 1) == quote or end = str.lentgth(). If in doubt call dequote(str.substring(begin, end), quote)

Parameters:
str input string from which to get the substring, must not be null
begin begin index for substring
end end index for substring
quote the quoting char
Returns:
dequoted string
Throws:
java.lang.IllegalArgumentException if string is incorrectly quoted
    public static String dequote(String strint beginint endchar quote)
    {
        // Is there anything to dequote?
        if (begin == end)
        {
            return "";
        }
        int endInt = str.indexOf(quotebegin);
        // If no quotes, return the original string
        // and save StringBuilder allocation/char copying
        if (endInt < 0)
        {
            return str.substring(beginend);
        }
        StringBuilder sb     = new StringBuilder(end - begin);
        int          beginInt = begin// need begin later
        do
        {
            if (((endInt + 1) >= end) || (str.charAt(endInt + 1) != quote))
            {
                throw new IllegalArgumentException(
                    "Internal quote not doubled in string '"
                    + str.substring(beginend) + "'");
            }
            sb.append(substring(strbeginIntendInt)).append(quote);
            beginInt = endInt + 2;
            endInt = str.indexOf(quotebeginInt);
        }
        while ((endInt >= 0) && (endInt < end));
        return sb.append(substring(strbeginIntend)).toString();
    }

    
Removes the surrounding quote and any double quote inside the string
Example:
 "hello""world" becomes hello"world
 

Parameters:
str input string to dequote
quote the quoting char
Returns:
dequoted String
    public static String dequoteFull(String strchar quote)
    {
        if (str == null)
        {
            return null;
        }
        return dequoteFull(str, 0, str.length(), quote);
    }
    public static String dequoteFull(String strint beginint endchar quote)
    {
        // If empty substring, return empty string
        if (begin == end)
        {
            return "";
        }
        // If not quoted, return string
        if (str.charAt(begin) != quote)
        {
            return str.substring(beginend);
        }
        int endInt = end - 1;
        if ((str.length() < 2) || (str.charAt(endInt) != quote))
        {
            throw new IllegalArgumentException(
                "Closing quote missing in string '"
                + substring(strbeginend) + "'");
        }
        return dequote(strbegin + 1, endIntquote);
    }
    public static String replace(String strString replString with)
    {
        int lastindex = 0;
        int pos = str.indexOf(repl);
        // If no replacement needed, return the original string
        // and save StringBuilder allocation/char copying
        if (pos < 0)
        {
            return str;
        }
        int          len     = repl.length();
        int          lendiff = with.length() - repl.length();
        StringBuilder out     =
            new StringBuilder((lendiff <= 0) ? str.length()
                : (str.length() + (10 * lendiff)));
        while(pos >= 0)
        {
            out.append(substring(strlastindexpos)).append(with);
            lastindex = pos + len;
            pos = str.indexOf(repllastindex);
        }
        return out.append(substring(strlastindexstr.length())).toString();
    }
    public static String replace(String strchar replString with)
    {
        int pos = str.indexOf(repl);
        // If no replacement needed, return the original string
        // and save StringBuilder allocation/char copying
        if (pos < 0)
        {
            return str;
        }
        int          len       = str.length();
        int          lendiff   = with.length() - 1;
        StringBuilder out       =
            new StringBuilder((lendiff <= 0) ? str.length()
                : (str.length() + (10 * lendiff)));
        int          lastindex = 0;
        whilepos >= 0)
        {
            out.append(substring(strlastindexpos)).append(with);
            lastindex = pos + 1;
            pos = str.indexOf(repllastindex);
        }
        return out.append(substring(strlastindexlen)).toString();
    }
    
    public static StringBuffer replace(
        StringBuffer outString sString replString with)
    {
        int lastindex = 0;
        int len = repl.length();
        int index = s.indexOf(repl);
        while (index >= 0)
        {
            // we have search string at position index
            out.append(substring(slastindexindex)).append(with);
            lastindex = index + len;
            index = s.indexOf(repllastindex);
        }
        return out.append(substring(slastindexlen));
    }
    public static StringBuilder replace(
        StringBuilder outString sString replString with)
    {
        int lastindex = 0;
        int len = repl.length();
        int index = s.indexOf(repl);
        while (index >= 0)
        {
            // we have search string at position index
            out.append(substring(slastindexindex)).append(with);
            lastindex = index + len;
            index = s.indexOf(repllastindex);
        }
        return out.append(substring(slastindexlen));
    }

    
Split a string into an array of strings arround a character separator. This function will be efficient for longer strings

Parameters:
str the string to be split
separator the separator character
Returns:
array of string subparts
    public static String[] splitLongString(String strchar separator)
    {
        int len = (str == null) ? 0 : str.length();
        if (str == null || len == 0)
        {
            return .;
        }
        int       oldPos = 0;
        ArrayList list = new ArrayList();
        int pos = str.indexOf(separator);
        while(pos >= 0)
        {
            list.add(substring(stroldPospos));
            oldPos = (pos + 1);
            pos = str.indexOf(separatoroldPos);
        }
        list.add(substring(stroldPoslen));
        return (String[]) list.toArray(.);
    }

    
Split a string into an array of strings arround a character separator. Each element can be optionally quoted by the quote character.
This function will be efficient for long strings

Parameters:
str the string to be split
separator the separator character
quote the quote character
Returns:
array of string subparts
Throws:
java.lang.IllegalArgumentException DOCUMENT ME!
    public static String[] splitLongString(
        String strchar separatorchar quote)
    {
        int len = (str == null) ? 0 : str.length();
        if (str == null || len == 0)
        {
            return .;
        }
        int       oldPos = 0;
        ArrayList list = new ArrayList();
        for (int pos = 0; pos < lenoldPos = ++pos)
        {
            // Skip quoted text, if any
            while ((pos < len) && (str.charAt(pos) == quote))
            {
                pos = str.indexOf(quotepos + 1) + 1;
                if (pos == 0)
                {
                    throw new IllegalArgumentException(
                        "Closing quote missing in string '" + str + "'");
                }
            }
            boolean quoted;
            if (pos != oldPos)
            {
                quoted = true;
                if ((pos < len) && (str.charAt(pos) != separator))
                {
                    throw new IllegalArgumentException(
                        "Separator must follow closing quote in string '"
                        + str + "'");
                }
            }
            else
            {
                quoted     = false;
                pos        = str.indexOf(separatorpos);
                if (pos < 0)
                {
                    pos = len;
                }
            }
            list.add(
                quoted ? dequote(stroldPos + 1, pos - 1, quote)
                    : substring(stroldPospos));
        }
        return (String[]) list.toArray(.);
    }

    
Split a string into an array of strings arround a character separator. This function will be efficient for short strings, for longer strings, another approach may be better

Parameters:
str the string to be split
separator the separator character
Returns:
array of string subparts
    public static String[] splitShortString(String strchar separator)
    {
        int len = (str == null) ? 0 : str.length();
        if (str == null || len == 0)
        {
            return ......;
        }
        int lastTokenIndex = 0;
        // Step 1: how many substrings?
        //      We exchange double scan time for less memory allocation
        for (int pos = str.indexOf(separator);
            pos >= 0; pos = str.indexOf(separatorpos + 1))
        {
            lastTokenIndex++;
        }
        // Step 2: allocate exact size array
        String[] list   = new String[lastTokenIndex + 1];
        int      oldPos = 0;
        // Step 3: retrieve substrings
        int pos = str.indexOf(separator);
        int i = 0;
        
        while (pos >= 0)
        {
            list[i++] = substring(stroldPospos);
            oldPos = (pos + 1);
            pos = str.indexOf(separatoroldPos);
        }
        list[lastTokenIndex] = substring(stroldPoslen);
        return list;
    }

    
Split a string into an array of strings arround a character separator. Each element can be optionally quoted by the quote character.
This function will be efficient for short strings, for longer strings, another approach may be better

Parameters:
str the string to be split
separator the separator character
quote the quote character
Returns:
array of string subparts
Throws:
java.lang.IllegalArgumentException DOCUMENT ME!
    public static String[] splitShortString(
        String strchar separatorchar quote)
    {
        int len = (str == null) ? 0 : str.length();
        if (str == null || len == 0)
        {
            return .;
        }
        // Step 1: how many substrings?
        //      We exchange double scan time for less memory allocation
        int tokenCount = 0;
        for (int pos = 0; pos < lenpos++)
        {
            tokenCount++;
            int oldPos = pos;
            // Skip quoted text, if any
            while ((pos < len) && (str.charAt(pos) == quote))
            {
                pos = str.indexOf(quotepos + 1) + 1;
                // pos == 0 is not found (-1 returned by indexOf + 1)
                if (pos == 0)
                {
                    throw new IllegalArgumentException(
                        "Closing quote missing in string '" + str + "'");
                }
            }
            if (pos != oldPos)
            {
                if ((pos < len) && (str.charAt(pos) != separator))
                {
                    throw new IllegalArgumentException(
                        "Separator must follow closing quote in strng '"
                        + str + "'");
                }
            }
            else
            {
                pos = str.indexOf(separatorpos);
                if (pos < 0)
                {
                    break;
                }
            }
        }
        // Main loop will finish one substring short when last char is separator
        if (str.charAt(len - 1) == separator)
        {
            tokenCount++;
        }
        // Step 2: allocate exact size array
        String[] list = new String[tokenCount];
        // Step 3: retrieve substrings
        // Note: on this pass we do not check for correctness,
        //       since we have already done so
        tokenCount--; // we want to stop one token short
        int oldPos = 0;
        for (int pos = 0, i = 0; i < tokenCounti++, oldPos = ++pos)
        {
            boolean quoted;
            // Skip quoted text, if any
            while (str.charAt(pos) == quote)
            {
                pos = str.indexOf(quotepos + 1) + 1;
            }
            if (pos != oldPos)
            {
                quoted = true;
                if (str.charAt(pos) != separator)
                {
                    throw new IllegalArgumentException(
                        "Separator must follow closing quote in strng '"
                        + str + "'");
                }
            }
            else
            {
                quoted     = false;
                pos        = str.indexOf(separatorpos);
            }
            list[i] =
                quoted ? dequote(stroldPos + 1, pos - 1, quote)
                    : substring(stroldPospos);
        }
        list[tokenCount] = dequoteFull(stroldPoslenquote);
        return list;
    }
    public static String substring(String strint beginint end)
    {
        if (begin == end)
        {
            return "";
        }
        return str.substring(beginend);
    }
    public static String[] trim(String[] strings)
    {
        if (strings == null)
        {
            return null;
        }
        for (int i = 0, len = strings.lengthi < leni++)
        {
            strings[i] = strings[i].trim();
        }
        return strings;
    }

    
Returns the minimum index >= 0, if any

Use to find the first of two characters in a string:
minIndex(s.indexOf('/'), indexOf('\'))

    public static int minIndex(int aint b)
    {
        return (a < 0) ? b
            : (b < 0) ? a
                : (a < b) ? a : b;
    }
New to GrepCode? Check out our FAQ X