⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 stringtools.java

📁 java base64
💻 JAVA
📖 第 1 页 / 共 3 页
字号:
    /**
     * convert a String into long pennies. It ignores invalid chars, lead trail, embedded spaces. Dash is treated as a
     * minus sign. 0 or 2 decimal places are permitted.
     *
     * @param numStr String to be parsed.
     * @return long pennies.
     * @throws NumberFormatException if the number is too big to fit in a long.
     * @noinspection WeakerAccess
     */
    public static long parseLongPennies( String numStr )
        {
        numStr = numStr.trim();
        // strip commas, spaces, + etc
        StringBuffer b = new StringBuffer( numStr.length() );
        boolean negative = false;
        int decpl = -1;
        for ( int i = 0; i < numStr.length(); i++ )
            {
            char c = numStr.charAt( i );
            switch ( c )
                {
                case '-':
                    negative = true;
                    break;

                case '.':
                    if ( decpl == -1 )
                        {
                        decpl = 0;
                        }
                    else
                        {
                        throw new NumberFormatException(
                                "more than one decimal point" );
                        }
                    break;

                case '0':
                case '1':
                case '2':
                case '3':
                case '4':
                case '5':
                case '6':
                case '7':
                case '8':
                case '9':
                    if ( decpl != -1 )
                        {
                        decpl++;
                        }
                    b.append( c );
                    break;

                default:
                    // ignore junk chars
                    break;
                }// end switch
            }// end for
        if ( numStr.length() != b.length() )
            {
            numStr = b.toString();
            }

        if ( numStr.length() == 0 )
            {
            return 0;
            }
        long num = Long.parseLong( numStr );
        if ( decpl == -1 || decpl == 0 )
            {
            num *= 100;
            }
        else if ( decpl == 2 )
            {/* it is fine as is */
            }

        else
            {
            throw new NumberFormatException( "wrong number of decimal places." );
            }

        if ( negative )
            {
            num = -num;
            }
        return num;
        }// end parseLongPennies

    /**
     * Print dollar currency, stored internally as scaled int. convert pennies to a string with a decorative decimal
     * point.
     *
     * @param pennies long amount in pennies.
     * @return amount with decorative decimal point, but no lead $.
     * @noinspection WeakerAccess
     */
    public static String penniesToString( long pennies )
        {
        boolean negative;
        if ( pennies < 0 )
            {
            pennies = -pennies;
            negative = true;
            }
        else
            {
            negative = false;
            }
        String s = Long.toString( pennies );
        int len = s.length();
        switch ( len )
            {
            case 1:
                s = "0.0" + s;
                break;
            case 2:
                s = "0." + s;
                break;
            default:
                s =
                        s.substring( 0, len - 2 ) + "." + s.substring( len - 2,
                                len );
                break;
            }// end switch
        if ( negative )
            {
            s = "-" + s;
            }
        return s;
        }// end penniesToString

    /**
     * Extracts a number from a string, returns 0 if malformed.
     *
     * @param s String containing the integer.
     * @return binary integer.
     */
    public static int pluck( String s )
        {
        int result = 0;
        try
            {
            result = Integer.parseInt( s );
            }
        catch ( NumberFormatException e )
            {
            // leave result at 0
            }
        return result;
        }// end pluck

    /**
     * used to prepare SQL string literals by doubling each embedded ' and wrapping in ' at each end. Further quoting is
     * required to use the results in Java String literals. If you use PreparedStatement, then this method is not
     * needed. The ' quoting is automatically handled for you.
     *
     * @param sql Raw SQL string literal
     * @return sql String literal enclosed in '
     * @noinspection WeakerAccess,SameParameterValue
     */
    public static String quoteSQL( String sql )
        {
        StringBuffer sb = new StringBuffer( sql.length() + 5 );
        sb.append( '\'' );
        for ( int i = 0; i < sql.length(); i++ )
            {
            char c = sql.charAt( i );
            if ( c == '\'' )
                {
                sb.append( "\'\'" );
                }
            else
                {
                sb.append( c );
                }
            }
        sb.append( '\'' );
        return sb.toString();
        }

    /**
     * Remove an unwanted bit of text at the head end of a string if it is present. Case sensitive.
     *
     * @param s    the string with the possibly wanted head. Will not be modified.
     * @param head the characters you want to remove from the start of the string s if they are present.
     * @return s with the head removed if it is present, otherwise s unmodified.
     */
    public static String removeHead( final String s, final String head )
        {
        if ( s != null && s.startsWith( head ) )
            {
            return s.substring( head.length() );
            }
        else
            {
            return s;
            }
        }

    /**
     * Remove an unwanted bit of text at the tail end of a string if it is present. Case sensitive.
     *
     * @param s    the string with the possibly wanted tail. Will not be modified.
     * @param tail the characters you want to remove from the end if they are present.
     * @return s with the tail removed if it is present, otherwise s unmodified.
     */
    public static String removeTail( final String s, final String tail )
        {
        if ( s != null && s.endsWith( tail ) )
            {
            return s.substring( 0, s.length() - tail.length() );
            }
        else
            {
            return s;
            }
        }

    /**
     * Produce a String of a given repeating character.
     *
     * @param c     the character to repeat
     * @param count the number of times to repeat
     * @return String, e.g. rep('*',4) returns "****"
     * @noinspection WeakerAccess,SameParameterValue
     */
    public static String rep( char c, int count )
        {
        char[] s = new char[count];
        for ( int i = 0; i < count; i++ )
            {
            s[ i ] = c;
            }
        return new String( s ).intern();
        }// end rep

    /**
     * Pads the string out to the given length by applying blanks on the right.
     *
     * @param s      String to be padded/chopped.
     * @param newLen length of new String desired.
     * @param chop   true if Strings longer than newLen should be truncated to newLen chars.
     * @return String padded on right/chopped to the desired length. Spaces are inserted on the right.
     * @noinspection WeakerAccess,SameParameterValue
     */
    public static String rightPad( String s, int newLen, boolean chop )
        {
        int grow = newLen - s.length();
        if ( grow <= 0 )
            {
            if ( chop )
                {
                return s.substring( 0, newLen );
                }
            else
                {
                return s;
                }
            }
        else if ( grow <= 30 )
            {
            return s + "                              ".substring( 0, grow );
            }
        else
            {
            return s + rep( ' ', grow );
            }
        }// end rightPad

    /**
     * Remove all spaces from a String.
     *
     * @param s String to strip of blanks.
     * @return String with all blanks, lead/trail/embedded removed.
     * @see #condense(String)
     */
    public static String squish( String s )
        {
        if ( s == null )
            {
            return null;
            }
        s = s.trim();
        if ( s.indexOf( ' ' ) < 0 )
            {
            return s;
            }
        int len = s.length();
        // have to use StringBuffer for JDK 1.1
        StringBuffer b = new StringBuffer( len - 1 );
        for ( int i = 0; i < len; i++ )
            {
            char c = s.charAt( i );
            if ( c != ' ' )
                {
                b.append( c );
                }
            }// end for
        return b.toString();
        }// end squish

    /**
     * convert to Book Title case, with first letter of each word capitalised. e.g. "handbook to HIGHER consciousness"
     * -> "Handbook to Higher Consciousness" e.g. "THE HISTORY OF THE U.S.A." -> "The History of the U.S.A." e.g. "THE
     * HISTORY OF THE USA" -> "The History of the Usa" (sorry about that.) Don't confuse this with Character.isTitleCase
     * which concerns ligatures.
     *
     * @param s String to convert. May be any mixture of case.
     * @return String with each word capitalised, except embedded words "the" "of" "to"
     * @noinspection WeakerAccess
     */
    public static String toBookTitleCase( String s )
        {
        char[] ca = s.toCharArray();
        // Track if we changed anything so that
        // we can avoid creating a duplicate String
        // object if the String is already in Title case.
        boolean changed = false;
        boolean capitalise = true;
        boolean firstCap = true;
        for ( int i = 0; i < ca.length; i++ )
            {
            char oldLetter = ca[ i ];
            if ( oldLetter <= '/'
                 || ':' <= oldLetter && oldLetter <= '?'
                 || ']' <= oldLetter && oldLetter <= '`' )
                {
                /* whitespace, control chars or punctuation */
                /* Next normal char should be capitalised */
                capitalise = true;
                }
            else
                {
                if ( capitalise && !firstCap )
                    {
                    // might be the_ of_ or to_
                    capitalise =
                            !( s.substring( i, Math.min( i + 4, s.length() ) )
                                    .equalsIgnoreCase( "the " )
                               || s.substring( i,
                                    Math.min( i + 3, s.length() ) )
                                    .equalsIgnoreCase( "of " )
                               || s.substring( i,
                                    Math.min( i + 3, s.length() ) )
                                    .equalsIgnoreCase( "to " ) );
                    }// end if
                char newLetter =
                        capitalise
                        ? Character.toUpperCase( oldLetter )
                        : Character.toLowerCase( oldLetter );
                ca[ i ] = newLetter;
                changed |= ( newLetter != oldLetter );
                capitalise = false;
                firstCap = false;

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -