com.webarch.common.lang.StringSeriesTools.java Source code

Java tutorial

Introduction

Here is the source code for com.webarch.common.lang.StringSeriesTools.java

Source

/*
        Copyright  DR.YangLong

        Licensed 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 com.webarch.common.lang;

import org.apache.commons.lang3.StringUtils;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * functional describe:
 *
 * @author DR.YangLong [410357434@163.com]
 * @version 1.0 2015/5/13 20:04 modify on 2015-7-1 add email,phone verify and object equals method
 */
public class StringSeriesTools {
    // ,????
    private static char[] numStr = new char[]{'','','', '', '', '', '', '', '', '?'};
    // ,????
    private static char[] unit = new char[]{' ','??','','?','','??'};

    /**
     * ????
     *
     * @param sourceStr ?
     * @param regex     ?
     * @return ?
     */
    public static List<String> findString(final String sourceStr, final String regex) {
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(sourceStr);
        List<String> list = new ArrayList<String>();
        while (matcher.find()) {
            list.add(matcher.group());
        }
        return list;
    }

    /**
     * ????
     *
     * @param sourceStr   
     * @param regex       
     * @param replacement ???
     * @return
     */
    public static String replaceAllMatch(final String sourceStr, final String regex, final String replacement) {
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(sourceStr);
        String source = matcher.replaceAll(replacement);
        return source;
    }

    /**
     * ?
     *
     * @param numString String
     * @return int
     */
    public static int string2Int(final String numString) {
        if (StringUtils.isNumeric(numString)) {
            return Integer.valueOf(numString);
        }
        return 0;
    }

    /**
     * ??0
     *
     * @param numString String
     * @return long
     */
    public static long string2Long(final String numString) {
        if (StringUtils.isNumeric(numString)) {
            return Long.valueOf(numString);
        }
        return 0;
    }

    /**
     * double,?0,?0.00
     *
     * @param numString 
     * @param pattern   ??
     * @return double
     */
    public static double string2double(final String numString, final String pattern) {
        try {
            double num = Double.parseDouble(numString);
            String defalutPattern = pattern == null ? "0.00" : pattern;
            DecimalFormat decimalFormat = new DecimalFormat(defalutPattern);
            num = Double.parseDouble(decimalFormat.format(num));
            return num;
        } catch (NumberFormatException e) {
            return 0;
        }
    }

    /**
     * int
     * ?ASCII048??,
     * ?charchar?int
     * int x = '6' - '0';x=6
     * char s = 6 + '0';s='6'
     *
     * @param ch 
     * @return
     */
    public static int char2num(char ch) {
        return ch - '0';
    }

    /**
     * ?double10n100=10^2
     *
     * @param str 
     * @return
     */
    public static double intStr2double(final String str) throws NumberFormatException {
        char[] strs = str.toCharArray();
        double result = 0;
        for (int i = 0;i < strs.length;i++) {
            double n = char2num(strs[i]);
            result += n * (Math.pow(10, i));
        }
        return result;
    }

    /**
     * ??double0.1n0.01=0.1^2
     *
     * @param str ?
     * @return
     */
    public static double dotStr2dot(final String str) throws NumberFormatException {
        char[] strs = str.toCharArray();
        double
                result = 0;
        for (int i = 0; i < strs.length; i++) {
            double n = char2num(strs[i]);
            result += n * (Math.pow(1 / 10.0, i + 1));
        }
        return result;
    }

    /**
     * ?double
     *
     * @return
     */
    public static double str2double(final String str) throws NumberFormatException {
        if ("".equals(str) || str.isEmpty()) {
            throw new NumberFormatException("NULL??");
        }
        int dotIndex = str.indexOf(".");
        if (dotIndex <= 0) {
            return intStr2double(str);
        } else {
            String intStr = str.substring(0, dotIndex);
            String dotStr = str.substring(dotIndex + 1, str.length());
            return intStr2double(intStr) + dotStr2dot(dotStr);
        }
    }

    /**
     * ?n?
     *
     * @param n    in<
     * @param type 1?23?
     * @return String
     */
    public static String getRanDomStr(final int n, final int type) {
        String[] charset;
        String[] charsetAll = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P",
                "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j",
                "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3",
                "4", "5", "6", "7", "8", "9"};
        String[] charsetNum = {"0", "1", "2", "3",
                "4", "5", "6", "7", "8", "9"};
        String[] charsetChar = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P",
                "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j",
                "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"};
        switch (type) {
            case 1:
                charset = charsetAll;
                break;
            case 2:
                charset = charsetNum;
                break;
            case 3:
                charset = charsetChar;
                break;
            default:
                charset = charsetAll;
        }
        Random random = new Random();
        String[] nonces = new String[n];
        //
        List<String> choose = new ArrayList<String>(charset.length);
        //??
        Collections.addAll(choose, charset);
        int nl = n;
        while (nl-- > 0) {
            int k = random.nextInt(choose.size());
            nonces[nl] = choose.get(k);
            choose.remove(k);
        }
        //?str
        String nonce = "";
        for (String str : nonces) {
            nonce += str;
        }
        return nonce;
    }

    /**
     * ??
     *
     * @return
     */
    public static String getNumber6FromRandom() {
        Random r = new Random();
        int xx = r.nextInt(1000000);
        while (xx < 100000) {
            xx = r.nextInt(1000000);
        }
        return String.valueOf(xx);
    }

    /**
     * @param num 
     * @return
     * @description ?
     */
    public static String getCnNumber(int num) {
        if (num < 0) {//??
            return null;
        }
        String strNum = new Integer(num).toString();
        // ?
        StringBuffer newStr = new StringBuffer("");
        for (int i = strNum.length() - 1; i >= 0; i--) {
            int index = Integer.parseInt(String.valueOf(strNum.charAt(strNum.length() - i - 1)));
            newStr.append(numStr[index]).append(unit[i]);
        }
        String result = newStr.toString().replaceAll("", "").
                replaceAll("?", "").
                replaceAll("", "").
                replaceFirst("??", "").
                replaceAll("+", "").replaceFirst("??", "??").trim();
        // ???
        if (result.endsWith("")) {
            result = result.substring(0, newStr.length() - 1);
        }
        return result;
    }

    /**
     * @param strNum 
     * @return
     * @description ?
     */
    public static String getCnNumber(String strNum) {
        if (strNum.indexOf("-") == 0) {//??
            return null;
        }
        // ?
        StringBuffer newStr = new StringBuffer("");
        if (strNum.indexOf(".") != -1) {//???
            strNum = strNum.substring(0, strNum.indexOf(".")).trim();
        } else {
            strNum = strNum.trim();
        }
        for (int i = strNum.length() - 1; i >= 0; i--) {
            int index = Integer.parseInt(String.valueOf(strNum.charAt(strNum.length() - i - 1)));
            newStr.append(numStr[index]).append(unit[i]);
        }
        String result = newStr.toString().replaceAll("", "").
                replaceAll("?", "").
                replaceAll("", "").
                replaceFirst("??", "").
                replaceAll("+", "").replaceFirst("??", "??");
        // ???
        if (result.endsWith("")) {
            result = result.substring(0, result.length() - 1);
        }
        return result;
    }

    /**
     * ?
     *
     * @param index
     * @return
     */
    public static String getCnNum(final String index) {
        String num = null;
        if (StringUtils.isNumeric(index)) {
            try {
                num = String.valueOf(numStr[Integer.parseInt(index)]);
            } catch (NumberFormatException e) {
                return num;
            }
        }
        return num;
    }

    /**
     * ?
     *
     * @param index
     * @return
     */
    public static String getCnNum(final int index) {
        String num = null;
        if (index >= 0 && index < numStr.length) {
            num = String.valueOf(numStr[index]);
        }
        return num;
    }

    /**
     * ?NULL,true?false
     *
     * @param str 
     * @return true/false
     */
    public static boolean isNullOrEmpty(final String str) {
        return str == null || "".equals(str);
    }

    /**
     * ?NULLtrue?false
     * @param str 
     * @return true/false
     */
    public static boolean isNullOrEmpty(final Object str){
        return str==null||"".equals(str.toString());
    }

    /**
     * ??
     * @param emailAdress ?
     * @return true/false
     */
    public static boolean verifyEmailAdress(String emailAdress){
        String regex="[\\w!#$%&'*+/=?^_`{|}~-]+(?:\\.[\\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\\w](?:[\\w-]*[\\w])?\\.)+[\\w](?:[\\w-]*[\\w])?";
        return null!=emailAdress&&emailAdress.matches(regex);
    }

    /**
     * ???
     * @param phoneNo ??
     * @return true/false
     */
    public static boolean verifyPhoneNum(String phoneNo){
        String regex="^((13[0-9])|(17[0,7])|(15[^4,\\D])||(18[0-9]))\\d{8}$";
        return null!=phoneNo&&phoneNo.matches(regex);
    }

    /**
     * 2?
     * @param ob1 1
     * @param ob2 2
     * @return true/false
     */
    public static boolean equalObject(Object ob1,Object ob2){
        return !(ob1==null||ob2==null)&&ob1.equals(ob2);
    }

    /**
     * 2String?,?
     * @param ob1 1
     * @param ob2 2
     * @return true/false
     */
    public static boolean equalStringObjectIgnoreCase(Object ob1,Object ob2){
        return !(ob1==null||ob2==null)&&(ob1.toString().equalsIgnoreCase(ob2.toString()));
    }

    /**
     *
     * @param array 
     * @param surffix ?
     * @return
     */
    public static String array2String(final String[] array,final String surffix){
        StringBuilder builder=new StringBuilder();
        for(int i=0;i<array.length;i++){
            if(i==array.length-1){
                builder.append(array[i]);
            }
            else {
                builder.append(array[i]).append(surffix);
            }
        }
        return builder.toString();
    }
}