Java常用工具类封装——String操作工具类

Java Character 类和Java String 类 Character 类用于对单个字符进行操作。Character 类在对象中包装一个基本类型的值。Java String 类字符串广泛应用 在 Java 编程中,在 Java 中字符串属于对象,Java 提供了 String 类来创建和操作字符串。 阅读详情

项目中经常需要用到String的一些操作,结合看到的一些前人的工具类抽取,编写了如下针对String的常用操作的工具类,供大家参考。

package com.mkyong.common;  
   
import java.util.ArrayList;  
import java.util.List;  
   
/** 
 *  
 * String工具类. <br> 
 *  
 * @author jiangshuai
 * @date 2017年04月24日 
 */  
public class StringUtil {  
   
    private static final int INDEX_NOT_FOUND = -1;  
    private static final String EMPTY = "";  
    /** 
     * <p> 
     * The maximum size to which the padding constant(s) can expand. 
     * </p> 
     */  
    private static final int PAD_LIMIT = 8192;  
   
    /** 
     * 功能:将半角的符号转换成全角符号.(即英文字符转中文字符) 
     *  
     * @author jiangshuai 
     * @param str 
     *            源字符串 
     * @return String 
     * @date 2017年04月24日 
     */  
    public static String changeToFull(String str) {  
        String source = "1234567890!@#$%^&*()abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_=+\\|[];:'\",<.>/?";  
        String[] decode = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "0",  
                "!", "@", "#", "$", "%", "︿", "&", "*", "(", ")", "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", "-", "_", "=", "+", "\", "|", "【", "】", ";", ":",  
                "'", "\"", ",", "〈", "。", "〉", "/", "?" };  
        String result = "";  
        for (int i = 0; i < str.length(); i++) {  
            int pos = source.indexOf(str.charAt(i));  
            if (pos != -1) {  
                result += decode[pos];  
            } else {  
                result += str.charAt(i);  
            }  
        }  
        return result;  
    }  
   
    /** 
     * 功能:cs串中是否一个都不包含字符数组searchChars中的字符。 
     *  
     * @author jiangshuai 
     * @param cs 
     *            字符串 
     * @param searchChars 
     *            字符数组 
     * @return boolean 都不包含返回true,否则返回false。 
     * @date 2017年04月24日 
     */  
    public static boolean containsNone(CharSequence cs, char... searchChars) {  
        if (cs == null || searchChars == null) {  
            return true;  
        }  
        int csLen = cs.length();  
        int csLast = csLen - 1;  
        int searchLen = searchChars.length;  
        int searchLast = searchLen - 1;  
        for (int i = 0; i < csLen; i++) {  
            char ch = cs.charAt(i);  
            for (int j = 0; j < searchLen; j++) {  
                if (searchChars[j] == ch) {  
                    if (Character.isHighSurrogate(ch)) {  
                        if (j == searchLast) {  
                            // missing low surrogate, fine, like  
                            // String.indexOf(String)  
                            return false;  
                        }  
                        if (i < csLast  
                                && searchChars[j + 1] == cs.charAt(i + 1)) {  
                            return false;  
                        }  
                    } else {  
                        // ch is in the Basic Multilingual Plane  
                        return false;  
                    }  
                }  
            }  
        }  
        return true;  
    }  
   
    /** 
     * <p> 
     * 编码为Unicode,格式 '\u0020'. 
     * </p> 
     *  
     * @author jiangshuai 
     *  
     *         <pre> 
     *   CharUtils.unicodeEscaped(' ') = "\u0020" 
     *   CharUtils.unicodeEscaped('A') = "\u0041" 
     * </pre> 
     *  
     * @param ch 
     *            源字符串 
     * @return 转码后的字符串 
     * @date 2017年04月24日 
     */  
    public static String unicodeEscaped(char ch) {  
        if (ch < 0x10) {  
            return "\\u000" + Integer.toHexString(ch);  
        } else if (ch < 0x100) {  
            return "\\u00" + Integer.toHexString(ch);  
        } else if (ch < 0x1000) {  
            return "\\u0" + Integer.toHexString(ch);  
        }  
        return "\\u" + Integer.toHexString(ch);  
    }  
   
    /** 
     * <p> 
     * 进行tostring操作,如果传入的是null,返回空字符串。 
     * </p> 
     * 
     * <pre> 
     * ObjectUtils.toString(null)         = "" 
     * ObjectUtils.toString("")           = "" 
     * ObjectUtils.toString("bat")        = "bat" 
     * ObjectUtils.toString(Boolean.TRUE) = "true" 
     * </pre> 
     * 
     * @param obj 
     *            源 
     * @return String 
     */  
    public static String toString(Object obj) {  
        return obj == null ? "" : obj.toString();  
    }  
   
    /** 
     * <p> 
     * 进行tostring操作,如果传入的是null,返回指定的默认值。 
     * </p> 
     * 
     * <pre> 
     * ObjectUtils.toString(null, null)           = null 
     * ObjectUtils.toString(null, "null")         = "null" 
     * ObjectUtils.toString("", "null")           = "" 
     * ObjectUtils.toString("bat", "null")        = "bat" 
     * ObjectUtils.toString(Boolean.TRUE, "null") = "true" 
     * </pre> 
     * 
     * @param obj 
     *            源 
     * @param nullStr 
     *            如果obj为null时返回这个指定值 
     * @return String 
     */  
    public static String toString(Object obj, String nullStr) {  
        return obj == null ? nullStr : obj.toString();  
    }  
   
    /** 
     * <p> 
     * 只从源字符串中移除指定开头子字符串. 
     * </p> 
     *  
     * <pre> 
     * StringUtil.removeStart(null, *)      = null 
     * StringUtil.removeStart("", *)        = "" 
     * StringUtil.removeStart(*, null)      = * 
     * StringUtil.removeStart("www.domain.com", "www.")   = "domain.com" 
     * StringUtil.removeStart("domain.com", "www.")       = "domain.com" 
     * StringUtil.removeStart("www.domain.com", "domain") = "www.domain.com" 
     * StringUtil.removeStart("abc", "")    = "abc" 
     * </pre> 
     * 
     * @param str 
     *            源字符串 
     * @param remove 
     *            将要被移除的子字符串 
     * @return String 
     */  
    public static String removeStart(String str, String remove) {  
        if (isEmpty(str) || isEmpty(remove)) {  
            return str;  
        }  
        if (str.startsWith(remove)) {  
            return str.substring(remove.length());  
        }  
        return str;  
    }  
   
    /** 
     * <p> 
     * 只从源字符串中移除指定结尾的子字符串. 
     * </p> 
     *  
     * <pre> 
     * StringUtil.removeEnd(null, *)      = null 
     * StringUtil.removeEnd("", *)        = "" 
     * StringUtil.removeEnd(*, null)      = * 
     * StringUtil.removeEnd("www.domain.com", ".com.")  = "www.domain.com" 
     * StringUtil.removeEnd("www.domain.com", ".com")   = "www.domain" 
     * StringUtil.removeEnd("www.domain.com", "domain") = "www.domain.com" 
     * StringUtil.removeEnd("abc", "")    = "abc" 
     * </pre> 
     * 
     * @param str 
     *            源字符串 
     * @param remove 
     *            将要被移除的子字符串 
     * @return String 
     */  
    public static String removeEnd(String str, String remove) {  
        if (isEmpty(str) || isEmpty(remove)) {  
            return str;  
        }  
        if (str.endsWith(remove)) {  
            return str.substring(0, str.length() - remove.length());  
        }  
        return str;  
    }  
   
    /** 
     * <p> 
     * 将一个字符串重复N次 
     * </p> 
     * 
     * <pre> 
     * StringUtil.repeat(null, 2) = null 
     * StringUtil.repeat("", 0)   = "" 
     * StringUtil.repeat("", 2)   = "" 
     * StringUtil.repeat("a", 3)  = "aaa" 
     * StringUtil.repeat("ab", 2) = "abab" 
     * StringUtil.repeat("a", -2) = "" 
     * </pre> 
     * 
     * @param str 
     *            源字符串 
     * @param repeat 
     *            重复的次数 
     * @return String 
     */  
    public static String repeat(String str, int repeat) {  
        // Performance tuned for 2.0 (JDK1.4)  
   
        if (str == null) {  
            return null;  
        }  
        if (repeat <= 0) {  
            return EMPTY;  
        }  
        int inputLength = str.length();  
        if (repeat == 1 || inputLength == 0) {  
            return str;  
        }  
        if (inputLength == 1 && repeat <= PAD_LIMIT) {  
            return repeat(str.charAt(0), repeat);  
        }  
   
        int outputLength = inputLength * repeat;  
        switch (inputLength) {  
        case 1:  
            return repeat(str.charAt(0), repeat);  
        case 2:  
            char ch0 = str.charAt(0);  
            char ch1 = str.charAt(1);  
            char[] output2 = new char[outputLength];  
            for (int i = repeat * 2 - 2; i >= 0; i--, i--) {  
                output2[i] = ch0;  
                output2[i + 1] = ch1;  
            }  
            return new String(output2);  
        default:  
            StringBuilder buf = new StringBuilder(outputLength);  
            for (int i = 0; i < repeat; i++) {  
                buf.append(str);  
            }  
            return buf.toString();  
        }  
    }  
   
    /** 
     * <p> 
     * 将一个字符串重复N次,并且中间加上指定的分隔符 
     * </p> 
     * 
     * <pre> 
     * StringUtil.repeat(null, null, 2) = null 
     * StringUtil.repeat(null, "x", 2)  = null 
     * StringUtil.repeat("", null, 0)   = "" 
     * StringUtil.repeat("", "", 2)     = "" 
     * StringUtil.repeat("", "x", 3)    = "xxx" 
     * StringUtil.repeat("?", ", ", 3)  = "?, ?, ?" 
     * </pre> 
     * 
     * @param str 
     *            源字符串 
     * @param separator 
     *            分隔符 
     * @param repeat 
     *            重复次数 
     * @return String 
     */  
    public static String repeat(String str, String separator, int repeat) {  
        if (str == null || separator == null) {  
            return repeat(str, repeat);  
        } else {  
            // given that repeat(String, int) is quite optimized, better to rely  
            // on it than try and splice this into it  
            String result = repeat(str + separator, repeat);  
            return removeEnd(result, separator);  
        }  
    }  
   
    /** 
     * <p> 
     * 将某个字符重复N次. 
     * </p> 
     * 
     * @param ch 
     *            某个字符 
     * @param repeat 
     *            重复次数 
     * @return String 
     */  
    public static String repeat(char ch, int repeat) {  
        char[] buf = new char[repeat];  
        for (int i = repeat - 1; i >= 0; i--) {  
            buf[i] = ch;  
        }  
        return new String(buf);  
    }  
   
    /** 
     * <p> 
     * 字符串长度达不到指定长度时,在字符串右边补指定的字符. 
     * </p> 
     *  
     * <pre> 
     * StringUtil.rightPad(null, *, *)     = null 
     * StringUtil.rightPad("", 3, 'z')     = "zzz" 
     * StringUtil.rightPad("bat", 3, 'z')  = "bat" 
     * StringUtil.rightPad("bat", 5, 'z')  = "batzz" 
     * StringUtil.rightPad("bat", 1, 'z')  = "bat" 
     * StringUtil.rightPad("bat", -1, 'z') = "bat" 
     * </pre> 
     * 
     * @param str 
     *            源字符串 
     * @param size 
     *            指定的长度 
     * @param padChar 
     *            进行补充的字符 
     * @return String 
     */  
    public static String rightPad(String str, int size, char padChar) {  
        if (str == null) {  
            return null;  
        }  
        int pads = size - str.length();  
        if (pads <= 0) {  
            return str; // returns original String when possible  
        }  
        if (pads > PAD_LIMIT) {  
            return rightPad(str, size, String.valueOf(padChar));  
        }  
        return str.concat(repeat(padChar, pads));  
    }  
   
    /** 
     * <p> 
     * 扩大字符串长度,从左边补充指定字符 
     * </p> 
     *  
     * <pre> 
     * StringUtil.rightPad(null, *, *)      = null 
     * StringUtil.rightPad("", 3, "z")      = "zzz" 
     * StringUtil.rightPad("bat", 3, "yz")  = "bat" 
     * StringUtil.rightPad("bat", 5, "yz")  = "batyz" 
     * StringUtil.rightPad("bat", 8, "yz")  = "batyzyzy" 
     * StringUtil.rightPad("bat", 1, "yz")  = "bat" 
     * StringUtil.rightPad("bat", -1, "yz") = "bat" 
     * StringUtil.rightPad("bat", 5, null)  = "bat  " 
     * StringUtil.rightPad("bat", 5, "")    = "bat  " 
     * </pre> 
     * 
     * @param str 
     *            源字符串 
     * @param size 
     *            扩大后的长度 
     * @param padStr 
     *            在右边补充的字符串 
     * @return String 
     */  
    public static String rightPad(String str, int size, String padStr) {  
        if (str == null) {  
            return null;  
        }  
        if (isEmpty(padStr)) {  
            padStr = " ";  
        }  
        int padLen = padStr.length();  
        int strLen = str.length();  
        int pads = size - strLen;  
        if (pads <= 0) {  
            return str; // returns original String when possible  
        }  
        if (padLen == 1 && pads <= PAD_LIMIT) {  
            return rightPad(str, size, padStr.charAt(0));  
        }  
   
        if (pads == padLen) {  
            return str.concat(padStr);  
        } else if (pads < padLen) {  
            return str.concat(padStr.substring(0, pads));  
        } else {  
            char[] padding = new char[pads];  
            char[] padChars = padStr.toCharArray();  
            for (int i = 0; i < pads; i++) {  
                padding[i] = padChars[i % padLen];  
            }  
            return str.concat(new String(padding));  
        }  
    }  
   
    /** 
     * <p> 
     * 扩大字符串长度,从左边补充空格 
     * </p> 
     * 
     * <pre> 
     * StringUtil.leftPad(null, *)   = null 
     * StringUtil.leftPad("", 3)     = "   " 
     * StringUtil.leftPad("bat", 3)  = "bat" 
     * StringUtil.leftPad("bat", 5)  = "  bat" 
     * StringUtil.leftPad("bat", 1)  = "bat" 
     * StringUtil.leftPad("bat", -1) = "bat" 
     * </pre> 
     * 
     * @param str 
     *            源字符串 
     * @param size 
     *            扩大后的长度 
     * @return String 
     */  
    public static String leftPad(String str, int size) {  
        return leftPad(str, size, ' ');  
    }  
   
    /** 
     * <p> 
     * 扩大字符串长度,从左边补充指定的字符 
     * </p> 
     * 
     * <pre> 
     * StringUtil.leftPad(null, *, *)     = null 
     * StringUtil.leftPad("", 3, 'z')     = "zzz" 
     * StringUtil.leftPad("bat", 3, 'z')  = "bat" 
     * StringUtil.leftPad("bat", 5, 'z')  = "zzbat" 
     * StringUtil.leftPad("bat", 1, 'z')  = "bat" 
     * StringUtil.leftPad("bat", -1, 'z') = "bat" 
     * </pre> 
     * 
     * @param str 
     *            源字符串 
     * @param size 
     *            扩大后的长度 
     * @param padStr 
     *            补充的字符 
     * @return String 
     */  
    public static String leftPad(String str, int size, char padChar) {  
        if (str == null) {  
            return null;  
        }  
        int pads = size - str.length();  
        if (pads <= 0) {  
            return str; // returns original String when possible  
        }  
        if (pads > PAD_LIMIT) {  
            return leftPad(str, size, String.valueOf(padChar));  
        }  
        return repeat(padChar, pads).concat(str);  
    }  
   
    /** 
     * <p> 
     * 扩大字符串长度,从左边补充指定的字符 
     * </p> 
     *  
     * <pre> 
     * StringUtil.leftPad(null, *, *)      = null 
     * StringUtil.leftPad("", 3, "z")      = "zzz" 
     * StringUtil.leftPad("bat", 3, "yz")  = "bat" 
     * StringUtil.leftPad("bat", 5, "yz")  = "yzbat" 
     * StringUtil.leftPad("bat", 8, "yz")  = "yzyzybat" 
     * StringUtil.leftPad("bat", 1, "yz")  = "bat" 
     * StringUtil.leftPad("bat", -1, "yz") = "bat" 
     * StringUtil.leftPad("bat", 5, null)  = "  bat" 
     * StringUtil.leftPad("bat", 5, "")    = "  bat" 
     * </pre> 
     * 
     * @param str 
     *            源字符串 
     * @param size 
     *            扩大后的长度 
     * @param padStr 
     *            补充的字符串 
     * @return String 
     */  
    public static String leftPad(String str, int size, String padStr) {  
        if (str == null) {  
            return null;  
        }  
        if (isEmpty(padStr)) {  
            padStr = " ";  
        }  
        int padLen = padStr.length();  
        int strLen = str.length();  
        int pads = size - strLen;  
        if (pads <= 0) {  
            return str; // returns original String when possible  
        }  
        if (padLen == 1 && pads <= PAD_LIMIT) {  
            return leftPad(str, size, padStr.charAt(0));  
        }  
   
        if (pads == padLen) {  
            return padStr.concat(str);  
        } else if (pads < padLen) {  
            return padStr.substring(0, pads).concat(str);  
        } else {  
            char[] padding = new char[pads];  
            char[] padChars = padStr.toCharArray();  
            for (int i = 0; i < pads; i++) {  
                padding[i] = padChars[i % padLen];  
            }  
            return new String(padding).concat(str);  
        }  
    }  
   
    /** 
     * <p> 
     * 扩大字符串长度并将现在的字符串居中,被扩大部分用空格填充。 
     * <p> 
     *  
     * <pre> 
     * StringUtil.center(null, *)   = null 
     * StringUtil.center("", 4)     = "    " 
     * StringUtil.center("ab", -1)  = "ab" 
     * StringUtil.center("ab", 4)   = " ab " 
     * StringUtil.center("abcd", 2) = "abcd" 
     * StringUtil.center("a", 4)    = " a  " 
     * </pre> 
     * 
     * @param str 
     *            源字符串 
     * @param size 
     *            扩大后的长度 
     * @return String 
     */  
    public static String center(String str, int size) {  
        return center(str, size, ' ');  
    }  
   
    /** 
     * <p> 
     * 将字符串长度修改为指定长度,并进行居中显示。 
     * </p> 
     * 
     * <pre> 
     * StringUtil.center(null, *, *)     = null 
     * StringUtil.center("", 4, ' ')     = "    " 
     * StringUtil.center("ab", -1, ' ')  = "ab" 
     * StringUtil.center("ab", 4, ' ')   = " ab" 
     * StringUtil.center("abcd", 2, ' ') = "abcd" 
     * StringUtil.center("a", 4, ' ')    = " a  " 
     * StringUtil.center("a", 4, 'y')    = "yayy" 
     * </pre> 
     * 
     * @param str 
     *            源字符串 
     * @param size 
     *            指定的长度 
     * @param padStr 
     *            长度不够时补充的字符串 
     * @return String 
     * @throws IllegalArgumentException 
     *             如果被补充字符串为 null或者 empty 
     */  
    public static String center(String str, int size, char padChar) {  
        if (str == null || size <= 0) {  
            return str;  
        }  
        int strLen = str.length();  
        int pads = size - strLen;  
        if (pads <= 0) {  
            return str;  
        }  
        str = leftPad(str, strLen + pads / 2, padChar);  
        str = rightPad(str, size, padChar);  
        return str;  
    }  
   
    /** 
     * <p> 
     * 将字符串长度修改为指定长度,并进行居中显示。 
     * </p> 
     * 
     * <pre> 
     * StringUtil.center(null, *, *)     = null 
     * StringUtil.center("", 4, " ")     = "    " 
     * StringUtil.center("ab", -1, " ")  = "ab" 
     * StringUtil.center("ab", 4, " ")   = " ab" 
     * StringUtil.center("abcd", 2, " ") = "abcd" 
     * StringUtil.center("a", 4, " ")    = " a  " 
     * StringUtil.center("a", 4, "yz")   = "yayz" 
     * StringUtil.center("abc", 7, null) = "  abc  " 
     * StringUtil.center("abc", 7, "")   = "  abc  " 
     * </pre> 
     * 
     * @param str 
     *            源字符串 
     * @param size 
     *            指定的长度 
     * @param padStr 
     *            长度不够时补充的字符串 
     * @return String 
     * @throws IllegalArgumentException 
     *             如果被补充字符串为 null或者 empty 
     */  
    public static String center(String str, int size, String padStr) {  
        if (str == null || size <= 0) {  
            return str;  
        }  
        if (isEmpty(padStr)) {  
            padStr = " ";  
        }  
        int strLen = str.length();  
        int pads = size - strLen;  
        if (pads <= 0) {  
            return str;  
        }  
        str = leftPad(str, strLen + pads / 2, padStr);  
        str = rightPad(str, size, padStr);  
        return str;  
    }  
   
    /** 
     * <p> 
     * 检查字符串是否全部为小写. 
     * </p> 
     *  
     * <pre> 
     * StringUtil.isAllLowerCase(null)   = false 
     * StringUtil.isAllLowerCase("")     = false 
     * StringUtil.isAllLowerCase("  ")   = false 
     * StringUtil.isAllLowerCase("abc")  = true 
     * StringUtil.isAllLowerCase("abC") = false 
     * </pre> 
     * 
     * @param cs 
     *            源字符串 
     * @return String 
     */  
    public static boolean isAllLowerCase(String cs) {  
        if (cs == null || isEmpty(cs)) {  
            return false;  
        }  
        int sz = cs.length();  
        for (int i = 0; i < sz; i++) {  
            if (Character.isLowerCase(cs.charAt(i)) == false) {  
                return false;  
            }  
        }  
        return true;  
    }  
   
    /** 
     * <p> 
     * 检查是否都是大写. 
     * </p> 
     *  
     * <pre> 
     * StringUtil.isAllUpperCase(null)   = false 
     * StringUtil.isAllUpperCase("")     = false 
     * StringUtil.isAllUpperCase("  ")   = false 
     * StringUtil.isAllUpperCase("ABC")  = true 
     * StringUtil.isAllUpperCase("aBC") = false 
     * </pre> 
     * 
     * @param cs 
     *            源字符串 
     * @return String 
     */  
    public static boolean isAllUpperCase(String cs) {  
        if (cs == null || StringUtil.isEmpty(cs)) {  
            return false;  
        }  
        int sz = cs.length();  
        for (int i = 0; i < sz; i++) {  
            if (Character.isUpperCase(cs.charAt(i)) == false) {  
                return false;  
            }  
        }  
        return true;  
    }  
   
    /** 
     * <p> 
     * 反转字符串. 
     * </p> 
     *  
     * <pre> 
     * StringUtil.reverse(null)  = null 
     * StringUtil.reverse("")    = "" 
     * StringUtil.reverse("bat") = "tab" 
     * </pre> 
     * 
     * @param str 
     *            源字符串 
     * @return String 
     */  
    public static String reverse(String str) {  
        if (str == null) {  
            return null;  
        }  
        return new StringBuilder(str).reverse().toString();  
    }  
   
    /** 
     * <p> 
     * 字符串达不到一定长度时在右边补空白. 
     * </p> 
     *  
     * <pre> 
     * StringUtil.rightPad(null, *)   = null 
     * StringUtil.rightPad("", 3)     = "   " 
     * StringUtil.rightPad("bat", 3)  = "bat" 
     * StringUtil.rightPad("bat", 5)  = "bat  " 
     * StringUtil.rightPad("bat", 1)  = "bat" 
     * StringUtil.rightPad("bat", -1) = "bat" 
     * </pre> 
     * 
     * @param str 
     *            源字符串 
     * @param size 
     *            指定的长度 
     * @return String 
     */  
    public static String rightPad(String str, int size) {  
        return rightPad(str, size, ' ');  
    }  
   
    /** 
     * 从右边截取字符串.</p> 
     *  
     * <pre> 
     * StringUtil.right(null, *)    = null 
     * StringUtil.right(*, -ve)     = "" 
     * StringUtil.right("", *)      = "" 
     * StringUtil.right("abc", 0)   = "" 
     * StringUtil.right("abc", 2)   = "bc" 
     * StringUtil.right("abc", 4)   = "abc" 
     * </pre> 
     *  
     * @param str 
     *            源字符串 
     * @param len 
     *            长度 
     * @return String 
     */  
    public static String right(String str, int len) {  
        if (str == null) {  
            return null;  
        }  
        if (len < 0) {  
            return EMPTY;  
        }  
        if (str.length() <= len) {  
            return str;  
        }  
        return str.substring(str.length() - len);  
    }  
   
    /** 
     * <p> 
     * 截取一个字符串的前几个. 
     * </p> 
     *  
     * <pre> 
     * StringUtil.left(null, *)    = null 
     * StringUtil.left(*, -ve)     = "" 
     * StringUtil.left("", *)      = "" 
     * StringUtil.left("abc", 0)   = "" 
     * StringUtil.left("abc", 2)   = "ab" 
     * StringUtil.left("abc", 4)   = "abc" 
     * </pre> 
     *  
     * @param str 
     *            源字符串 
     * @param len 
     *            截取的长度 
     * @return the String 
     */  
    public static String left(String str, int len) {  
        if (str == null) {  
            return null;  
        }  
        if (len < 0) {  
            return EMPTY;  
        }  
        if (str.length() <= len) {  
            return str;  
        }  
        return str.substring(0, len);  
    }  
   
    /** 
     * <p> 
     * 得到tag字符串中间的子字符串,只返回第一个匹配项。 
     * </p> 
     *  
     * <pre> 
     * StringUtil.substringBetween(null, *)            = null 
     * StringUtil.substringBetween("", "")             = "" 
     * StringUtil.substringBetween("", "tag")          = null 
     * StringUtil.substringBetween("tagabctag", null)  = null 
     * StringUtil.substringBetween("tagabctag", "")    = "" 
     * StringUtil.substringBetween("tagabctag", "tag") = "abc" 
     * </pre> 
     *  
     * @param str 
     *            源字符串。 
     * @param tag 
     *            标识字符串。 
     * @return String 子字符串, 如果没有符合要求的,返回{@code null}。 
     */  
    public static String substringBetween(String str, String tag) {  
        return substringBetween(str, tag, tag);  
    }  
   
    /** 
     * <p> 
     * 得到两个字符串中间的子字符串,只返回第一个匹配项。 
     * </p> 
     *  
     * <pre> 
     * StringUtil.substringBetween("wx[b]yz", "[", "]") = "b" 
     * StringUtil.substringBetween(null, *, *)          = null 
     * StringUtil.substringBetween(*, null, *)          = null 
     * StringUtil.substringBetween(*, *, null)          = null 
     * StringUtil.substringBetween("", "", "")          = "" 
     * StringUtil.substringBetween("", "", "]")         = null 
     * StringUtil.substringBetween("", "[", "]")        = null 
     * StringUtil.substringBetween("yabcz", "", "")     = "" 
     * StringUtil.substringBetween("yabcz", "y", "z")   = "abc" 
     * StringUtil.substringBetween("yabczyabcz", "y", "z")   = "abc" 
     * </pre> 
     *  
     * @param str 
     *            源字符串 
     * @param open 
     *            起字符串。 
     * @param close 
     *            末字符串。 
     * @return String 子字符串, 如果没有符合要求的,返回{@code null}。 
     */  
    public static String substringBetween(String str, String open, String close) {  
        if (str == null || open == null || close == null) {  
            return null;  
        }  
        int start = str.indexOf(open);  
        if (start != INDEX_NOT_FOUND) {  
            int end = str.indexOf(close, start + open.length());  
            if (end != INDEX_NOT_FOUND) {  
                return str.substring(start + open.length(), end);  
            }  
        }  
        return null;  
    }  
   
    /** 
     * <p> 
     * 得到两个字符串中间的子字符串,所有匹配项组合为数组并返回。 
     * </p> 
     *  
     * <pre> 
     * StringUtil.substringsBetween("[a][b][c]", "[", "]") = ["a","b","c"] 
     * StringUtil.substringsBetween(null, *, *)            = null 
     * StringUtil.substringsBetween(*, null, *)            = null 
     * StringUtil.substringsBetween(*, *, null)            = null 
     * StringUtil.substringsBetween("", "[", "]")          = [] 
     * </pre> 
     * 
     * @param str 
     *            源字符串 
     * @param open 
     *            起字符串。 
     * @param close 
     *            末字符串。 
     * @return String 子字符串数组, 如果没有符合要求的,返回{@code null}。 
     */  
    public static String[] substringsBetween(String str, String open,  
            String close) {  
        if (str == null || isEmpty(open) || isEmpty(close)) {  
            return null;  
        }  
        int strLen = str.length();  
        if (strLen == 0) {  
            return new String[0];  
        }  
        int closeLen = close.length();  
        int openLen = open.length();  
        List<String> list = new ArrayList<String>();  
        int pos = 0;  
        while (pos < strLen - closeLen) {  
            int start = str.indexOf(open, pos);  
            if (start < 0) {  
                break;  
            }  
            start += openLen;  
            int end = str.indexOf(close, start);  
            if (end < 0) {  
                break;  
            }  
            list.add(str.substring(start, end));  
            pos = end + closeLen;  
        }  
        if (list.isEmpty()) {  
            return null;  
        }  
        return list.toArray(new String[list.size()]);  
    }  
   
    /** 
     * 功能:切换字符串中的所有字母大小写。<br/> 
     *  
     * <pre> 
     * StringUtil.swapCase(null)                 = null 
     * StringUtil.swapCase("")                   = "" 
     * StringUtil.swapCase("The dog has a BONE") = "tHE DOG HAS A bone" 
     * </pre> 
     *  
     * 
     * @param str 
     *            源字符串 
     * @return String 
     */  
    public static String swapCase(String str) {  
        if (StringUtil.isEmpty(str)) {  
            return str;  
        }  
        char[] buffer = str.toCharArray();  
   
        boolean whitespace = true;  
   
        for (int i = 0; i < buffer.length; i++) {  
            char ch = buffer[i];  
            if (Character.isUpperCase(ch)) {  
                buffer[i] = Character.toLowerCase(ch);  
                whitespace = false;  
            } else if (Character.isTitleCase(ch)) {  
                buffer[i] = Character.toLowerCase(ch);  
                whitespace = false;  
            } else if (Character.isLowerCase(ch)) {  
                if (whitespace) {  
                    buffer[i] = Character.toTitleCase(ch);  
                    whitespace = false;  
                } else {  
                    buffer[i] = Character.toUpperCase(ch);  
                }  
            } else {  
                whitespace = Character.isWhitespace(ch);  
            }  
        }  
        return new String(buffer);  
    }  
   
    /** 
     * 功能:截取出最后一个标志位之后的字符串.<br/> 
     * 如果sourceStr为empty或者expr为null,直接返回源字符串。<br/> 
     * 如果expr长度为0,直接返回sourceStr。<br/> 
     * 如果expr在sourceStr中不存在,直接返回sourceStr。<br/> 
     *  
     * @author jiangshuai 
     * @date 2017年04月24日 
     * @param sourceStr 
     *            被截取的字符串 
     * @param expr 
     *            分隔符 
     * @return String 
     */  
    public static String substringAfterLast(String sourceStr, String expr) {  
        if (isEmpty(sourceStr) || expr == null) {  
            return sourceStr;  
        }  
        if (expr.length() == 0) {  
            return sourceStr;  
        }  
   
        int pos = sourceStr.lastIndexOf(expr);  
        if (pos == -1) {  
            return sourceStr;  
        }  
        return sourceStr.substring(pos + expr.length());  
    }  
   
    /** 
     * 功能:截取出最后一个标志位之前的字符串.<br/> 
     * 如果sourceStr为empty或者expr为null,直接返回源字符串。<br/> 
     * 如果expr长度为0,直接返回sourceStr。<br/> 
     * 如果expr在sourceStr中不存在,直接返回sourceStr。<br/> 
     *  
     * @author jiangshuai 
     * @date 2017年04月24日 
     * @param sourceStr 
     *            被截取的字符串 
     * @param expr 
     *            分隔符 
     * @return String 
     */  
    public static String substringBeforeLast(String sourceStr, String expr) {  
        if (isEmpty(sourceStr) || expr == null) {  
            return sourceStr;  
        }  
        if (expr.length() == 0) {  
            return sourceStr;  
        }  
        int pos = sourceStr.lastIndexOf(expr);  
        if (pos == -1) {  
            return sourceStr;  
        }  
        return sourceStr.substring(0, pos);  
    }  
   
    /** 
     * 功能:截取出第一个标志位之后的字符串.<br/> 
     * 如果sourceStr为empty或者expr为null,直接返回源字符串。<br/> 
     * 如果expr长度为0,直接返回sourceStr。<br/> 
     * 如果expr在sourceStr中不存在,直接返回sourceStr。<br/> 
     *  
     * @author jiangshuai 
     * @date 2017年04月24日 
     * @param sourceStr 
     *            被截取的字符串 
     * @param expr 
     *            分隔符 
     * @return String 
     */  
    public static String substringAfter(String sourceStr, String expr) {  
        if (isEmpty(sourceStr) || expr == null) {  
            return sourceStr;  
        }  
        if (expr.length() == 0) {  
            return sourceStr;  
        }  
   
        int pos = sourceStr.indexOf(expr);  
        if (pos == -1) {  
            return sourceStr;  
        }  
        return sourceStr.substring(pos + expr.length());  
    }  
   
    /** 
     * 功能:截取出第一个标志位之前的字符串.<br/> 
     * 如果sourceStr为empty或者expr为null,直接返回源字符串。<br/> 
     * 如果expr长度为0,直接返回sourceStr。<br/> 
     * 如果expr在sourceStr中不存在,直接返回sourceStr。<br/> 
     * 如果expr在sourceStr中存在不止一个,以第一个位置为准。 
     *  
     * @author jiangshuai 
     * @date 2017年04月24日 
     * @param sourceStr 
     *            被截取的字符串 
     * @param expr 
     *            分隔符 
     * @return String 
     */  
    public static String substringBefore(String sourceStr, String expr) {  
        if (isEmpty(sourceStr) || expr == null) {  
            return sourceStr;  
        }  
        if (expr.length() == 0) {  
            return sourceStr;  
        }  
        int pos = sourceStr.indexOf(expr);  
        if (pos == -1) {  
            return sourceStr;  
        }  
        return sourceStr.substring(0, pos);  
    }  
   
    /** 
     * 功能:检查这个字符串是不是空字符串。<br/> 
     * 如果这个字符串为null或者trim后为空字符串则返回true,否则返回false。 
     *  
     * @author jiangshuai
     * @date 2017年04月24日 
     * @param chkStr 
     *            被检查的字符串 
     * @return boolean 
     */  
    public static boolean isEmpty(String chkStr) {  
        if (chkStr == null) {  
            return true;  
        } else {  
            return "".equals(chkStr.trim()) ? true : false;  
        }  
    }  
   
    /** 
     * 如果字符串没有超过最长显示长度返回原字符串,否则从开头截取指定长度并加...返回。 
     *  
     * @param str 
     *            原字符串 
     * @param length 
     *            字符串最长显示的长度 
     * @return 转换后的字符串 
     */  
    public static String trimString(String str, int length) {  
        if (str == null) {  
            return "";  
        } else if (str.length() > length) {  
            return str.substring(0, length - 3) + "...";  
        } else {  
            return str;  
        }  
    }  
   
}  


保姆级教程:在Davinci Configurator里配置BswM的ECU状态机(附状态切换流程图) 本文提供了一份详细的AUTOSAR BswM模块配置指南,通过Davinci Configurator工具实现ECU状态机的构建与管理。内容涵盖从模式请求端口创建到状态切换规则定义的全流程,特别针对Ecu State Handling进行了深入解析,并附有状态切换流程图,帮助汽车电子工程师高效完成ECU状态管理配置。 阅读详情

相关推荐

WRF后处理避坑指南:从namelist配置到降水计算的全流程解析

本文提供了一份详尽的WRF模式后处理避坑指南,涵盖从理解wrfout文件结构、核心变量解析到累计降水计算与专业气象图绘制的全流程。重点解析了RAINC与RAINNC的正确处理方法,并分享了使用wrf-python库高效绘制位势高度叠加风场图、累计降水图等专业图表的实战技巧与代码,旨在帮助用户规避常见错误,提升后处理效率与图表质量。

weixin_29200485的博客 353

Java 对象如何安全的 toString

如果我们的对象为空对象的时候,我们再使用 toString() 方法,我们将会得到空对象的异常。这个对象有可能就是 String 对象,也有可能是其他的对象。如下面的 2 行语句: 如果你执行上面 2 行语句的话,铁定会抛出下面的空对象异常。如何让 Java 能够 toString 又不抛出异常呢?我们可以使用 Apache commons.lang3 提供的 toString() 方法。如下面显示的使用用例: 如果我们输入的对象为 NULL 的话,上面的语句将会输出一个指定的字符串而不抛出空异常。

HONEY MOOSE 1060

二维“能量源”(电场、磁场、功率)入射边界设置方法

comsol光学仿真设计相关学习笔记和经验 1. 二维“能量源”(电场、磁场、功率)入射边界设置方法 2.边界条件设置薄膜材料

VJCP_90909Bu0的博客 5193

【常用工具类】ObjectUtils 全面总结 ,真的太方便了

ObjectUtils 全面总结

qq_43571809的博客 8602

一文详细讲解CRM系统(附架构图、流程、功能介绍)

专为中小企业量身打造高性价比的数字化转型路径!企业如何用CRM才能真正做到降本增效?今天,就用一文讲清这些问题!读完本文,你将清楚得了解CRM的概念、框架、流程、功能、企业成功案例,文末还有常见问题解答。

Dabeishandong的博客 9928

电网渗透之终端安全

        电力系统安全不仅关系到电网的稳定运行,也关系到国家能源安全和国计民生,甚至关系到国家的安全和利益,电力系统由于结构复杂多样、分布广泛、重要性高,一旦系统瘫痪影响巨大,因此,极容易成为敌对势力攻击的首选目标。随着信息安全暴露面迅速增加,将给公司网络安全防线带来严峻挑战。       监控、保障这些电力系统安全运行变的尤为重要。内部安全防护产品有防火墙、纵向加密、反向隔离设备等...

guapi007008的博客 2721

java 常用工具类的使用<二>

一、String工具类 1 package com.mkyong.common; 2 3 import java.util.ArrayList; 4 import java.util.List; 5 6 /** 7 * 8 * String工具类. <br> 9 * ...

weixin_34319111的博客 393

二、FM1288调试方案-工具软件使用

分析音频数据的软件需要满足以下几点:1、能打开原始pcm音频文件;2、基本的音频播放软件的操作;3、能查看分析音频数据的频率成分;4、能查看分析音频音量幅度;5、能完成基本音频处理:降噪、音量增幅限幅、滤波和均衡;

优快云mianfeixiazai001的博客 1294

Object类中常用的toString方法详解

基本介绍 toString方法是Object类中常用的一个方法,使用时有以下两种情况 (1)默认情况(未被重写的时候) 会默认返回:全类名(包名+类名)+@+哈希值的十六进制 在Object类中toString方法的源码是这样定义的 public String toString() { return getClass().getName() + "@" + Integer.toHexString(hashCode()); } (2)被重写的情况 一般情况下,我们经常会重写toSt

m0_61373339的博客 6003

【Windows Server 2019】Active Directory Certificate Services 证书颁发机构的安装,配置和管理Ⅰ——AD CS的安装和配置

博文主要介绍了Windows Server 2019的证书颁发机构的安装和配置方法。

VMware, Windows, Linux, Cisco, Container, Kubernetes, Kali 4833

十四种逻辑器件综合对比——《器件手册--逻辑器件》

逻辑器件是数字电路中最基本的逻辑单元,用于实现基本的逻辑运算,如与、或、非、异或等。逻辑门根据输入信号的组合产生相应的输出信号。与门:只有当所有输入信号都为高电平时,输出才为高电平。或门:只要有一个输入信号为高电平,输出就为高电平。非门:输出信号与输入信号相反。异或门:当两个输入信号不同时,输出为高电平;相同则输出为低电平。用于对输入信号进行反相操作,即将高电平转换为低电平,低电平转换为高电平。常用于信号的反相处理和逻辑电平的转换。

XU157303764的博客 2030

Object 类中toString()的使用

Object 类中toString()的使用 1.相关概念 当我们输出一个对象的引用时,实际上就是调用当前对象的toString()方法 Object类中toString方法的定义如下: public String toString() { return getClass().getName() + "@" + Integer.toHexString(hashCode()); } 像String、Date、File、包装类等都重写了Object类中的toString方法,使得在

ispringmw的博客 653

ZYNQ BRAM实现PS与PL数据交互

有时CPU需要与PL进行小批量的数据交换,可以通过BRAM模块,也就是Block RAM实现此要求。本章通过Zynq的GP Master接口读写PL端的BRAM,实现与PL的交互。在本实验中加入了自定义的FPGA程序,并利用AXI4总线进行配置,通知其何时读写BRAM。以下为本实验原理图,CPU通过AXI BRAM Controller读取BRAM数据,CPU仅配置自定义的PL BRAM Controller 的寄存器,不通过它读写数据。

baidu_34971492的博客 2276

Java之String类常用操作

public String(byte[] bytes,String charsetName)':通过使用指定的字符集解码当前参数中的字节数组来构造新的String。public String(byte[] bytes):通过使用平台的默认字符集解码当前参数中的字节数组来构造新的String。2、常量+变量 或者 变量+常量:都会通过new的方式创建一个新的字符串,返回堆空间中此字符串对象的地址。Serializable:可序列化的接口,凡是实现此接口的类的对象就可以通过网络或者本地流进行数据的传输。

python全栈 6386

迈瑞BS系列全自动生化分析仪LIS协议接口手册(内含HL7和ASTM)

迈瑞BS系列全自动生化分析仪LIS协议接口手册,内含HL7和ASTM)

精雕软件(JDpaint) 5.5 绿色版

精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版

Java常用工具类---Reflect反射工具类、String字符串工具类

package com.jarvis.base.util; /** * * * @Title: ReflectHelper.java * @Package com.jarvis.base.util * @Description: 反射工具类 * @version V1.0 */ public class ReflectHelper { /** * 提指定的类载入...

zhang150114的博客 1013

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

【Java编程动手学】Java常用工具类

Java常用工具类摘要 Java提供了丰富的工具类库,主要包括: String类:提供字符串操作方法如charAt()、equals()、substring()等,示例展示了字符串截取、替换、大小写转换等操作。 Runtime类:用于获取JVM运行环境信息,包括内存状态、处理器数量,并可通过exec()执行外部命令。 System类:提供系统级操作,如获取系统属性、环境变量,以及数组复制和程序退出等功能。 Math类:包含基本数学运算方法,如绝对值、幂运算、三角函数等,以及数学常数PI和E。 这些工具类简化

杰西笔记 946

java 反射工具类_java常用工具类 Reflect反射工具类、String字符串工具类

本文实例为大家分享了java常用工具类的具体代码,供大家参考,具体内容如下Reflect反射工具类package com.jarvis.base.util;/***** @Title: ReflectHelper.java* @Package com.jarvis.base.util* @Description: 反射工具类* @version V1.0*/public class Reflect...

weixin_29523709的博客 469

Java 常用工具类:String、Date、Math 及其高效使用

String类的高效使用可以显著提升字符串操作的性能,尤其是在进行多次拼接时,要优先使用或。Date类及 Java 8 新日期 API 提供了更加灵活和准确的日期时间处理方式,尽量避免直接使用Date类,建议使用LocalDate或。Math类提供了常见的数学方法,能够满足大多数开发需求。在性能要求较高的场景下,要注意算法优化。通过掌握这三个工具类的高效使用,你将能够在实际开发中事半功倍。不断实践这些技巧,并根据项目需求灵活运用这些工具类,能帮助你编写更简洁、更高效、更易维护的代码。

一名热衷于技术的全栈开发者,专注于前端与后端的全面技术探索。在这里,我将分享我在技术领域的学习与成长,助力更多开发者的进步。 651

java中string工具类_Java 常用工具类之 String 类

String 类的特点:字符串对象一旦被初始化就不会被改变.//以下代码的区别:String s = "abc"; // 在常量池中创建一个字符串对象, 池中没有就建立, 池中有,直接用.String s1 = new String("abc"); // 在堆内存中创建两个对象, 一个为 new 对象, 一个为字符串对象 "abc"System.out.println(s==s1); // fal...

weixin_39559333的博客 608

Java中的字符串操作类【String】与八种封装类

Java中的字符串操作类【String】与八种封装类 一、String类如何创建对象,有哪些常用方法? public final class String String类---表示一个字符串类【处理字符串数据的操作方法】 String类是使用final修饰符修饰的,说明它没有子类,不可被继承。 Java程序中的所有字符串文字(例如"abc")都被实现为此类的实例。 字符串不变; 它们的值...

weixin_52192654的博客 1422

Java中String类的使用

今天来复习复习Java中String类的使用。Java字符串String从表面上看,字符串就是双引号之间的数据,例如"Hello World",在Java中,字符串其实就是一个String类的对象,可以这样来定义一个字符串:String str1="Hello World";//第一种方法 String str2=new String("Hello World");//第二种方法这两种都可以创建字...

xkfanhua的博客 9266

Java开发经验——Java开发常用工具类实战总结

本文介绍了Java开发中常用的工具类,包括Apache Commons Collections的SetUtils、Google Guava的Sets、Apache Commons Lang的ArrayUtils等,以及它们在集合操作、数组操作、字符串处理、JSON处理等方面的应用。文章还涉及了Optional类、Money工具类、JDK流式函数等,旨在提高Java开发效率和代码质量。

庄小焱 1852

12.Java 核心基础全解析:接口、String、包装类与常用工具类

interface 接口,界面接口不是类,没有class,是java文件,用interface接入接口类的标志 class接口中没有正常属性,属性默认被public static final 修饰 属性都是静态常量;//默认被修饰 可以不写 属性是静态常量必须要有默认值;接口中的方法默认都是抽象方法,没有方法体,默认被abstract修饰;//方法默认被抽象修饰 abstract不用写但是jdk8以后可以被default和static修饰的方法可以有方法体接口中不能有构造方法,即不能创建对象。

2301_80238602的博客 1137

Java中String类的常见操作Api

Java中String常见api操作

. 1256
上一篇: Java实现ArrayList去重复值
下一篇: Java常用工具类封装——连接数据库的工具类
Yes_JiangShuai
博客等级 码龄10年 149粉丝 249原创
评论 4
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值