String字符串方法匯總


String字符串方法匯總

package com.tz.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import sun.misc.BASE64Encoder;

public class StringUtils {
    
    /**
     * 判斷一個元素是否為空,如果為空true 否則false
     * 方法名:isEmpty
     */
    public static boolean isEmpty(String content){
        return null!=content && "".equals(content);
    }
    
    /**
     * 字符串非空判斷
     * 方法名:isNotEmpty
     */
    public static boolean isNotEmpty(String content){
        return !isEmpty(content);
    }

    
    /**
     * 判斷當年是不是閏年,如果是true否則false
     * 方法名:isLeapYear
     */
    public static boolean isLeapYear(int year){
        return (year%4==0 && year%100!=0)  ||  year%400==0;
    }
    
    /**
     * 獲取一年中某個月的天數
     * 方法名:getMonthDay
     */
    public static int getMonthDay(int year,int month){
        int result = 31;    
        switch (month) {
                case 1:
                case 3:
                case 5:
                case 7:
                case 8:
                case 10:
                case 12:
                    result = 31;
                break;
                case 4:
                case 6:
                case 9:
                case 11:
                    result = 30;
                break;
            case 2:
                result = StringUtils.isLeapYear(year)?29:28;
                break;
            default:
                result = 31;
                break;
        }
        return result;
    }
    
    
    
    /**
     * pattern:
     *  理論上講日期格式表達式包含全部26個英文字母的大小寫,不過它們中的一些字母只是被預留了,並沒有確切的含義。目前有效的字母及它們所代表的含義如下:
                中文解釋含義:
            G:年代標識,表示是公元前還是公元后
            y:年份
            M:月份
            d:日
            h:小時,從1到12,分上下午
            H:小時,從0到23
            m:分鍾
            s:秒
            S:毫秒
            E:一周中的第幾天,對應星期幾,第一天為星期日,於此類推
            z:時區
            D:一年中的第幾天
            F:這一天所對應的星期幾在該月中是第幾次出現
            w:一年中的第幾個星期
            W:一個月中的第幾個星期
            a:上午/下午標識
            k:小時,從1到24
            K:小時,從0到11,區分上下午
                在日期格式表達式中出現的所有字母,在進行日期格式化操作后,都將被其所代表的含義對應的屬性值所替換,並且對某些字母來說,重復次數的不同,格式化后的結果也會有所不同。請看下面的例子:
     * 字符串格式編程日期
     * 方法名:stringToDate
     */
    public static Date stringToDate(String dateString,String pattern) throws ParseException{
        return new SimpleDateFormat(pattern).parse(dateString);
    }
    
    /**
     * 日期格式轉變成字符串
     * 方法名:dateToString
     */
    public static String dateToString(Date date,String pattern) throws ParseException{
        return new SimpleDateFormat(pattern).format(date);
    }
    
    /**
     * 將一個數字個格式化成為你的需要的金額【數字會四舍五入】
     * eg:doubleToString(12.5698,"#.##")===12.57
     * eg:doubleToString(12.5698,"0.00")===12.57
     * eg:doubleToString(12,"0.00")===12.00
     * eg:doubleToString(12,"#.##")===12
     * 方法名:doubleToString
     */
    public static String doubleToString(Double num,String pattern) throws ParseException{
        return new DecimalFormat(pattern).format(num);
    }
    
    /**
     * 替換字符串中所有的空格
     * 方法名:replaceAllTrim
     */
    public static String replaceAllTrim(String content){
        return content.replaceAll("\\s*", "");
    }
    
    /**
     * 判斷一個字符是不是中文
     * 方法名:isChineseChar
     */
    public static boolean isChineseChar(char c) {
        try {
            return String.valueOf(c).getBytes("GBK").length>1;
        } catch (Exception e) {
            return false;
        }
    }
    
    /**
     * 截取==我z中國 subString("我z中國",3)===我z<br/>
     * 方法名:subString
     */
    public static String subString(String string,int count){
        if(isEmpty(string))return "";
        int start=0;
        StringBuilder builder = new StringBuilder();
        for (int i = start; i < count; i++) {
            char c=string.charAt(i);
            builder.append(c);
            if(isChineseChar(c)){//判斷一個字符是不是漢字
                --count;
            }
        }
        return builder.toString();
    }
    
    
    /**
     * 獲取文件的后綴
     * 方法名:getExt
     */
    public static String getExt(String path){
        if(isEmpty(path))return path;
        String ext = path.substring(path.lastIndexOf(".")+1);
        return ext;
    }
    
    /**
     * 獲取帶有點的后綴
     * 方法名:getExtPonit
     */
    public static String getExtPoint(String path){
        if(isEmpty(path))return path;
        String ext = path.substring(path.lastIndexOf("."));
        return ext;
    }
    
    /**
     * 獲取文件的名稱
     * 方法名:getFileName
     */
    public static String getFileName(String path){
        if(isEmpty(path))return path;
        String filename = path.substring(path.lastIndexOf("/")+1, path.lastIndexOf("."));
        return filename;
    }
    
    /**
     * 驗證碼,文件隨機數
     * 隨即生產隨即數,
     * 可以用來生產tocken字符串等.
     * @param length 生成長度
     * @return 隨即數字符串.
     */
    public static String getRandomString(int length) {
        StringBuffer bu = new StringBuffer();
        String[] arr = { "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c",
                "d", "e", "f", "g", "h", "i", "j", "k", "m", "n", "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", "P",
                "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };
        Random random = new Random();
        while (bu.length() < length) {
            String temp = arr[random.nextInt(57)];
            if (bu.indexOf(temp) == -1) {
                bu.append(temp);
            }
        }
        return bu.toString();
    }
    
    /**
     * 獲取隨機文件名
     * 方法名:getNewFileName
     */
    public static String getNewFileName(String filename){
        return new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+"_"+getRandomString(5)+getExtPoint(filename);
    }
    
    /**
     * 根據用戶ID獲取文件隨機名
     * 方法名:getNewFileName
     */
    public static String getNewFileName(String filename,Integer userId){
        return new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+"_"+getRandomString(5)+"_"+userId+getExtPoint(filename);
    }
    
    /** 
     * 方法名:md5
     * @param src
     * @return byte[]
     */
    public static byte[] md5(String src) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            byte[] md = md5.digest(src.getBytes());
            return md;
        } catch (Exception e) {
        }
        return null; 
    }
    
    /**
     * MD5加載
     * 方法名:md5Base64
     * @param str
     * @return String
     */
    public static String md5Base64(String str) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            return base64Encode(md5.digest(str.getBytes()));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }
    
    public static String base64Encode(byte[] b) {
        if (b == null) {
            return null;
        }
        return new BASE64Encoder().encode(b);
    }
    
    /**
     * 凱撒密碼加密
     * 方法名:encryption
     * @param str
     * @param k
     * @return String
     */
    public static String encryption(String str,int k){
        String string = "";
        for (int i = 0; i < str.length(); i++) {
            char c= str.charAt(i);
            if(c>='a' && c<='z'){
                c += k%26;
                if(c<'a'){
                    c+=26;
                }
                if(c>'z'){
                    c-=26;
                }
            }else if(c>='A' && c<='Z'){
                c+=k%26;
                if(c<'A'){
                    c+=26;
                }
                if(c>'Z'){
                    c-=26;
                }
            }
            string+=c;
        }
        return string;
    }
    
    /**
     * 凱撒密碼解密
     * 方法名:dencryption
     * @param str
     * @param n
     * @return String
     */
    public static String dencryption(String str,int n){
        String string = "";
        int k = Integer.parseInt("-"+n);
        for (int i = 0; i < str.length(); i++) {
            char c= str.charAt(i);
            if(c>='a' && c<='z'){
                c += k%26;
                if(c<'a'){
                    c+=26;
                }
                if(c>'z'){
                    c-=26;
                }
            }else if(c>='A' && c<='Z'){
                c+=k%26;
                if(c<'A'){
                    c+=26;
                }
                if(c>'Z'){
                    c-=26;
                }
            }
            string+=c;
        }
        return string;
    }
    
    
    /**
     * 根據后綴判斷是不是圖片
     * 方法名:isImage
     * @param ext
     * @return boolean
     */
    public static boolean isImage(String ext) {
        return ext.toLowerCase().matches("jpg|gif|bmp|png|jpeg");
    }
    
    /**
     * 根據后綴判斷是不是offce文檔
     * 方法名:isImage
     * @param ext
     * @return boolean
     */
    public static boolean isDoc(String ext) {
        return ext.toLowerCase().matches("doc|docx|xls|xlsx|pdf|txt|ppt|pptx");
    }
    
    /**
     * 根據后綴判斷是不是音頻
     * 方法名:isImage
     * @param ext
     * @return boolean
     */
    public static boolean isVideo(String ext) {
        return ext.toLowerCase().matches("mp4|flv|mp3");
    }

    
    /**
     * 替換標簽符號位轉義符號
     * 方法名:htmlEncode
     * @param txt
     * @return String
     */
    public static String htmlEncode(String txt) {
        if (null != txt) {
            txt = txt.replace("&", "&amp;").replace("&amp;amp;", "&amp;")
                    .replace("&amp;quot;", "&quot;").replace("\"", "&quot;")
                    .replace("&amp;lt;", "&lt;").replace("<", "&lt;")
                    .replace("&amp;gt;", "&gt;").replace(">", "&gt;")
                    .replace("&amp;nbsp;", "&nbsp;");
        }
        return txt;
    }

    /**
     * 整數的轉換與0補齊
     * @param str 轉換的數字
     * @param length 轉換的長度。不夠0補齊.
     * @return
     */
    public static String formatNO(int str, int length) {
        float ver = Float.parseFloat(System
                .getProperty("java.specification.version"));
        String laststr = "";
        if (ver < 1.5) {
            try {
                NumberFormat formater = NumberFormat.getNumberInstance();
                formater.setMinimumIntegerDigits(length);
                laststr = formater.format(str).toString().replace(",", "");
            } catch (Exception e) {
                System.out.println("格式化字符串時的錯誤信息:" + e.getMessage());
            }
        } else {
            Integer[] arr = new Integer[1];
            arr[0] = new Integer(str);
            laststr = String.format("%0" + length + "d", arr);
        }
        return laststr;
    }
    
    /***
     * 字符串數組轉換成字符串
     * @param strings
     */
    public static String arrToString(String[] strings, String separtor) {
        StringBuffer buffer = new StringBuffer();
        if (strings != null) {
            for (String string : strings) {
                buffer.append(string + separtor);
            }
            String result = buffer.toString();
            return result.substring(0, result.length() - 1);
        } else {
            return "";
        }
    }
    
    /** 首字母轉換為大寫 **/
    public static String toUpperCaseFirst(String text) {
        return text.substring(0, 1).toUpperCase() + text.substring(1);
    }
    
    /** 首字母轉換為大寫 **/
    public static String getFirstChar(String text) {
        return text.substring(0, 1).toUpperCase();
    }

    /** 首字母轉換為小寫 **/
    public static String toLowerCaseFirst(String text) {
        return text.substring(0, 1).toLowerCase() + text.substring(1);
    }
    /**
     * @作用:判斷是否為數字
     */
    public static boolean isNumeric(String str) {
        Matcher isNum = Pattern.compile("(-|\\+)?[0-9]+(.[0-9]+\\+)?").matcher(
                str);
        return isNum.matches();
    }
    
    
    /**
     * 判斷字符串是否都是數字組成
     * @param numString
     */
    public static boolean isNumber(String numString) {
        return StringUtils.isNumeric(numString);
    }

    /**
     * 郵箱驗證 方法名:isEmail 
     * @param str
     * @return boolean
     */
    public static boolean isEmail(String email) {
        boolean flag = false;
        try {
            String check = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
            Pattern regex = Pattern.compile(check);
            Matcher matcher = regex.matcher(email);
            flag = matcher.matches();
        } catch (Exception e) {
            flag = false;
        }
        return flag;
    }

    /**
     * 驗證手機號碼
     * @param mobiles
     */
    public static boolean isMobile(String mobiles) {
        boolean flag = false;
        try {
            Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");
            Matcher m = p.matcher(mobiles);
            flag = m.matches();
        } catch (Exception e) {
            flag = false;
        }
        return flag;
    }

    /**
     * 網絡地址驗證 方法名:isHomepage
     * @param str
     * @return boolean
     */
    public static boolean isHomepage(String str) {
        String regex = "http://(([a-zA-z0-9]|-){1,}\\.){1,}[a-zA-z0-9]{1,}-*";
        return match(regex, str);
    }

    private static boolean match(String regex, String str) {
        Pattern pattern = Pattern.compile(regex);// 將給定的正則表達式編譯到具有給定標志的模式中
        Matcher matcher = pattern.matcher(str);// 模式進行匹配字符
        return matcher.matches();
    }
    
    /**
     * 方法名:listToString
     * @param params
     * @param sepator
     * @return String
     */
    public static String listToString(List<String> params, String sepator) {
        if (params.size() > 0) {
            StringBuffer buffer = new StringBuffer();
            for (String string : params) {
                buffer.append(string + sepator);
            }
            String result = buffer.toString();
            return result.substring(0, result.length());
        } else {
            return "";
        }
    }

    
    public static void main(String[] args) throws ParseException {
        
//        List<String> idStrings= new ArrayList<>();
//        idStrings.add("1");
//        idStrings.add("2");
//        idStrings.add("3");
//        idStrings.add("4");
        
//        System.out.println(listToString(idStrings, "#"));
//        String text="<script>alert(1)</script>";
//        System.out.println(htmlEncode(text));

//        System.out.println(formatNO(1,3));
//        System.out.println(formatNO(123,6));
        
        //字符串處理,文件名和后綴 路徑的問題---項目中的文件上傳--URL路徑設計理念---磁盤路徑是一樣
//        String path="/ccc/keke.mp4";
//        System.out.println(getNewFileName(path));
//        System.out.println(getNewFileName(path,88));
//        System.out.println(getNewFileName(path,78));
        
        //加鹽加密 --凱撒密碼
//        System.out.println(md5Base64(md5Base64("keke_123456")));
//        System.out.println(md5Base64("keke_123456"));

//        System.out.println(encryption("我ab課cdZ",10));
//        System.out.println(dencryption("我cd課ef", 10));
        
        //百度---字符串驗證---數字,金額,郵箱,中文,

//        System.out.println(getExt(path));
//        System.out.println(getExtPonit(path));
//        System.out.println(getFileName(path));
//        
//        //隨機文件名,訂單號----文件名處理處理,文件重命名---經驗之談
//        
//        //毫無意義---隨機或者UUID的方式
//        Random random =new Random();
//        System.out.println(random.nextInt(1000));
    
//        System.out.println(getRandomString(10));
//        System.out.println(getRandomString(14));
//        System.out.println(getRandomString(5));
//        System.out.println(getRandomString(35));
//        System.out.println(getRandomString(50));
        
//        //真正的uuid  機器碼+時間+ip地址+ UUID
//        System.out.println(UUID.randomUUID().toString());
//        System.out.println(UUID.randomUUID().toString());
//        System.out.println(UUID.randomUUID().toString());
        
        //結合業務---有意義
//        20A160C315E1215D36-d2114A5-1.jpg
        //Random隨機數
        
        //System---獲取操作系統里面的一些常量信息
//        System.out.println(System.getProperty("os.name"));
//        System.out.println(System.getProperty("java.home"));
//        System.out.println(System.getProperty("user.dir"));

        //RunTime
//        Runtime runtime = Runtime.getRuntime();
//        long max=runtime.maxMemory()/1024/1024;
//        long total=runtime.totalMemory()/1024/1024;
//        long free=runtime.freeMemory()/1024/1024;
//        System.out.println("運行時的對象:"+runtime.availableProcessors());
//        System.out.println("最大內存數"+max);//
//        System.out.println("空閑的內存數"+free);
//        System.out.println("總內存數"+total);
//        System.out.println("剩余內存大小:"+(max-total+free));
        
        //Math函數---數學--三角函數,絕對性,平方根,大小運算,四舍五入 乘方
////        Math.toDegrees(hudu)//弧度轉成角度
//        System.out.println(Math.toDegrees(3.14));//角度轉成弧度
//        System.out.println(Math.toRadians(90));
//        圓的周長==2πr
//        180 = π
//        90 =90π/180--直角三角形
        //正弦---對邊/斜邊
//        System.out.println(Math.sin(Math.toRadians(30)));
//        System.out.println(Math.sin(Math.toRadians(60)));
//        //余弦---鄰邊/斜邊
//        System.out.println(Math.cos(Math.toRadians(30)));
//        System.out.println(Math.cos(Math.toRadians(60)));
//        
//        //反余弦
//        System.out.println(Math.acos(Math.toRadians(30)));
////        System.out.println(Math.acos(Math.toRadians(60)));
//        //反正弦
//        System.out.println(Math.asin(Math.toRadians(30)));
////        System.out.println(Math.asin(Math.toRadians(60)));
//        
//        //正切
//        System.out.println(Math.tan(Math.toRadians(30)));
        
        //通用--字符串 Math
//        double s = 21.2554;
//        System.out.println(Math.floor(s));//21
//        System.out.println(Math.ceil(s));//22

//        //四舍五入--無法保留小數
//        double c =3.569;
//        System.out.println(Math.round(c));
//        String cstr= new DecimalFormat("#.##").format(c);
//        System.out.println(cstr);
//        
//        //平方根
//        System.out.println(Math.sqrt(3));
//        //立方根
//        System.out.println(Math.cbrt(27));
        //次冪
//        System.out.println(Math.exp(3));
        
//        //a的b次方
//        System.out.println(Math.pow(3, 2));//3*3
//        System.out.println(Math.pow(3, 3));//3*3*3
        
    
//        System.out.println(Math.PI);//π--圓周率
//        System.out.println(Math.E);//自然指數
        
        //最大值 最小值
//        Math.min(12, 1);//1
//        Math.max(12, 1);//12
        
        
//        //絕對值
//        System.out.println(Math.abs(-2));
//        System.out.println(Math.abs(2));
        

        //java基礎數據數字--布爾類型
        //byte short int long float double char 數字類型
        //boolean 布爾

        //BigDecimal 在講一次
//        BigDecimal b1= new BigDecimal(1);
//        BigDecimal b2= new BigDecimal(3);
//        BigDecimal b3=b1.add(b2);//相加
//        BigDecimal b3=b1.subtract(b2);//相減
//        BigDecimal b3=b1.multiply(b2);//相乘
//        BigDecimal b3=b1.divide(b2,18,BigDecimal.ROUND_HALF_UP);//相除
//        System.out.println(b3);
        
//        System.out.println(1/3d);

    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM