关于字符串操作工具类源码


格式化日期对象,返回格式化后的字符串

	/**
	 * 格式化日期对象,返回格式化后的字符串。
	 * 
	 * @param date
	 * @return
	 */
	public static String date2String(Date date) {
		return formatDate(date, "yyyy-MM-dd HH:mm:ss");
	}

	public static String simpleDate(Date date) {
		return formatDate(date, "yyyy-MM-dd");
	}

格式化日期对象,返回中文日期字符串

/**
	 * 格式化日期对象,返回中文日期字符串
	 * 
	 * @param date
	 * @return 中文日期
	 */
	public static String simpleDateCH(Date date) {
		return formatDate(date, "yyyy年MM月dd日");
	}

根据文件名,读取文件内容,文件内容返回字符串

/**
	 * 根据文件名,读取文件内容,文件内容返回字符串
	 * 
	 * @param filePath
	 * @return
	 */
	public static String readFile(String filePath, String charset) {
		if (charset == null)
			charset = "UTF-8";
		java.io.File file = null;
		java.io.BufferedReader br = null;
		try {
			file = new java.io.File(filePath);
			br = new java.io.BufferedReader(new java.io.InputStreamReader(
					new java.io.FileInputStream(file), charset));
			String line = br.readLine();
			StringBuffer sb = new StringBuffer();
			while (line != null) {
				sb.append(line);
				line = br.readLine();
			}
			return sb.toString();
		} catch (java.io.IOException ioe) {
		} finally {
			try {
				if (br != null)
					br.close();
			} catch (Exception e) {
			}
		}
		return null;
	}

字符串替换

/**
	 * 字符串替换
	 * 
	 * @param oldString
	 * @param oldSubString
	 * @param newSubString
	 * @return
	 */
	public static String replaceString(String oldString, String oldSubString,
			String newSubString) {
		StringBuffer rtnValue = new StringBuffer();
		try {
			if (oldString.length() < oldSubString.length()) // 如果原始字符串比原始字符子串还小的话,返回原始字符串
				return oldString;
			String tempString = "";
			for (int oldstrCount = 0; oldstrCount <= oldString.length()
					- oldSubString.length(); oldstrCount++) {
				tempString = oldString.substring(oldstrCount, oldstrCount
						+ oldSubString.length());
				if (tempString.equals(oldSubString)) {
					rtnValue.append(newSubString);
					oldstrCount = oldstrCount + oldSubString.length() - 1;
					if (oldstrCount + 1 > oldString.length()
							- oldSubString.length())
						rtnValue.append(oldString.substring(oldstrCount + 1));
				} else {
					rtnValue.append(oldString.charAt(oldstrCount));
					if (oldstrCount == oldString.length()
							- oldSubString.length()) {
						rtnValue.append(oldString.substring(oldstrCount + 1));
					}
				}
			}
		} catch (Exception e) {
			return oldString;
		}
		return rtnValue.toString();
	}

生成随机数字

/**
	 * 生成随机数字
	 * 
	 * @param length
	 * @return
	 */
	public static final String randomNumber(int length) {
		char[] numbersAndLetters = null;
		java.util.Random randGen = null;
		if (length < 1) {
			return null;
		}
		// Init of pseudo random number generator.
		if (randGen == null) {
			if (randGen == null) {
				randGen = new java.util.Random();
				// Also initialize the numbersAndLetters array
				numbersAndLetters = ("0123456789").toCharArray();
			}
		}
		// Create a char buffer to put random letters and numbers in.
		char[] randBuffer = new char[length];
		for (int i = 0; i < randBuffer.length; i++) {
			randBuffer[i] = numbersAndLetters[randGen.nextInt(9)];
		}
		return new String(randBuffer);
	}

生成随机字符串

/**
	 * 生成随机字符串
	 * 
	 * @param length
	 * @return
	 */
	public static final String randomString(int length) {
		char[] numbersAndLetters = null;
		java.util.Random randGen = null;
		if (length < 1) {
			return null;
		}
		// Init of pseudo random number generator.
		if (randGen == null) {
			if (randGen == null) {
				randGen = new java.util.Random();
				// Also initialize the numbersAndLetters array
				numbersAndLetters = ("0123456789abcdefghijklmnopqrstuvwxyz"
						+ "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ").toCharArray();
			}
		}
		// Create a char buffer to put random letters and numbers in.
		char[] randBuffer = new char[length];
		for (int i = 0; i < randBuffer.length; i++) {
			randBuffer[i] = numbersAndLetters[randGen.nextInt(71)];
		}
		return new String(randBuffer);
	}

字符串分割

	/**
	 * 字符串分割
	 * 
	 * @param oldString
	 * @param delim
	 * @return
	 */
	public static String[] split(String oldString, String delim) {
		if (oldString == null)
			return null;
		String[] newArray = null;
		java.util.StringTokenizer st = new java.util.StringTokenizer(oldString,
				delim);
		newArray = new String[st.countTokens()];
		int count = 0;
		while (st.hasMoreTokens()) {
			newArray[count] = st.nextToken().trim();
			count++;
		}
		return newArray;
	}

格式化日期

/**
	 * 格式化日期
	 * 
	 * @param d
	 * @return
	 */
	public static String formatDate(Date d) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return sdf.format(d);
	}

	/**
	 * 格式化日期
	 * 
	 * @param d
	 * @return
	 */
	public static String formatDatess(Date d) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
		return sdf.format(d);
	}

	/**
	 * 格式化日期
	 * 
	 * @param d
	 * @return
	 */
	public static String formatDates(Date d) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		return sdf.format(d);
	}

	/**
	 * 格式化日期
	 * 
	 * @param d
	 * @return
	 */
	public static String formatDateMM(Date d) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd,HH:mm");
		return sdf.format(d);
	}

MD5加密

/**
	 * MD5加密
	 * 
	 * @param orgString
	 * @return
	 * @throws java.security.NoSuchAlgorithmException
	 * @throws java.io.UnsupportedEncodingException
	 */
	public static String md5Encrypt(String orgString) {
		try {
			java.security.MessageDigest md = java.security.MessageDigest
					.getInstance("MD5");
			md.update(orgString.getBytes());
			byte[] b = md.digest();
			return byte2hex(b);
		} catch (java.security.NoSuchAlgorithmException ne) {
			throw new IllegalStateException(
					"System doesn't support your  Algorithm.");
		}
	}

	public static String md5Encrypt(String orgString, String charSet) {
		try {
			java.security.MessageDigest md = java.security.MessageDigest
					.getInstance("MD5");
			md.update(orgString.getBytes(charSet));
			byte[] b = md.digest();
			return byte2hex(b);
		} catch (java.security.NoSuchAlgorithmException ne) {
			throw new IllegalStateException(
					"System doesn't support your  Algorithm.");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			throw new IllegalStateException("System doesn't support chaset");
		}
	}

将字节数组转换成16进制字符串

/**
	 * 将字节数组转换成16进制字符串
	 * 
	 * @param b
	 * @return
	 */
	private static String byte2hex(byte[] b) // 二行制转字符串

	{
		String hs = "";
		String stmp = "";
		for (int n = 0; n < b.length; n++) {
			stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
			if (stmp.length() == 1)
				hs = hs + "0" + stmp;
			else
				hs = hs + stmp;
		}
	

金钱相关处理

/**
	 * 从数据库读出钱时,调用这个函数(数据库保存的金额为分,前台显示为元)
	 */
	public static String formatMoneyFromData(String price) {
		if (price == null)
			return price;
		if (price.indexOf(".") == 0)
			return "0";
		if (price.indexOf(".") > 0)
			price = price.substring(0, price.indexOf("."));
		int money = Integer.parseInt(price);
		int mod = money % 100;
		int imod = money / 100;
		String temp = "";
		// if ( mod == 0 )
		// temp = new String ("00");
		// else
		if ((mod < 10) && (mod > -10))
			temp = ".0" + mod;
		else
			temp = "." + mod;
		return "" + imod + temp;
	}

	/**
	 * 将分格式化为元,去掉小数点后的0
	 * 
	 * @param price
	 * @return
	 */
	public static String formatMoney(String price) {
		Long money = Long.valueOf(price) / 100;
		money.shortValue();
		return money.toString();
	}

获取两个日期之间的天数

/**
	 * 获取两个日期之间的天数
	 * 
	 * @param startDate
	 * @param endDate
	 * @return
	 * @throws ParseException
	 */
	public static long getCompareDate(String startDate, String endDate)
			throws ParseException {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		Date date1 = formatter.parse(startDate);
		Date date2 = formatter.parse(endDate);
		long l = date2.getTime() - date1.getTime();
		long d = l / (24 * 60 * 60 * 1000);
		return d;
	}

	public static int longToInt(long value) {
		return Integer.valueOf(Long.valueOf(value).toString());
	}

半角转全角

/**
	 * 半角转全角
	 * 
	 * @param input
	 *            String.
	 * @return 全角字符串.
	 */
	public static String toSBC(String input) {
		if (input == null)
			return null;
		try {
			char c[] = input.toCharArray();
			for (int i = 0; i < c.length; i++) {
				if (c[i] == ' ') {
					c[i] = 'u3000';
				} else if (c[i] < '177') {
					c[i] = (char) (c[i] + 65248);

				}
			}
			return new String(c);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return input;
	}

全角转半角

/**
	 * 全角转半角
	 * 
	 * @param input
	 *            String.
	 * @return 半角字符串
	 */
	@SuppressWarnings("unused")
	public static String toDBC(String input) {
		if (input == null)
			return null;
		try {
			char c[] = input.toCharArray();
			for (int i = 0; i < c.length; i++) {
				if (c[i] == 'u3000') {
					c[i] = ' ';
				} else if (c[i] > 'uFF00' && c[i] < 'uFF5F') {
					c[i] = (char) (c[i] - 65248);

				}
			}
			String returnString = new String(c);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return input;
	}

特殊字符转义

/**
	 * 特殊字符转义
	 * 
	 * @param input
	 *            String.
	 * @return 转义后的字符串
	 */
	public static String enCode(String content) {
		String str1 = content.replace("<", "&lt;");
		String str2 = str1.replace(">", "&gt;");
		String str3 = str2.replace("'", "&apos;");
		String str4 = str3.replace(" ", "&nbsp;");
		String str5 = str4.replace("
", "<br>");
		String str6 = str5.replace(""", "&quot;");
		String str7 = str6.replace("&", "&amp;");
		return str7;

	}

判断是否是数字

	/**
	 * 判断是否是数字
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isNumeric(String str) {
		Pattern pattern = Pattern.compile("[0-9]*");
		return pattern.matcher(str).matches();
	}

判断是否为英文

/**
	 * 判断是否为英文
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isEnglish(String str) {
		Pattern pattern = Pattern.compile("^[A-Za-z]+$");
		return pattern.matcher(str).matches();
	}

转换为unicode编码

/**
	 * 转换为unicode编码
	 * 
	 * @author zhanglei
	 * @param sourceStr
	 * @return
	 */
	public static String toUnicode(String sourceStr) {
		char[] tmpBuffer = sourceStr.toCharArray();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < tmpBuffer.length; i++) {
			UnicodeBlock ub = UnicodeBlock.of(tmpBuffer[i]);
			if (ub == UnicodeBlock.BASIC_LATIN) {
				sb.append(tmpBuffer[i]);
			} else if (ub == UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
				int s = (int) tmpBuffer[i] - 65248;
				sb.append((char) s);
			} else {
				int s = (int) tmpBuffer[i];
				String hexStr = Integer.toHexString(s);
				String unicode = "\u" + hexStr;
				sb.append(unicode.toLowerCase());
			}
		}
		return sb.toString();
	}

截取字符串区分中英文

/**
	 * 截取字符串区分中英文
	 * 
	 * @param s
	 * @param length
	 * @return
	 */
	public static String subString(String s, int length) {
		StringBuffer o = new StringBuffer();
		if (StringUtil.isBlank(s)) {
			return "";
		}
		int size = 0;
		for (int i = 0; i < s.length(); i++) {

			if (s.charAt(i) >= 0x0391 && s.charAt(i) <= 0xffe5) {
				size += 2;
				if (size > length) {
					break;
				} else {
					o.append(s.charAt(i));
				}
			} else {
				size += 1;
				if (size > length) {
					break;
				} else {
					o.append(s.charAt(i));
				}

			}
		}
		return o.toString();
	}

判断是否为中文

/**
	 * 判断是否为中文
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isChinaString(String str) {

		// 字符串中是否有中文
		Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
		Matcher m = p.matcher(str);
		return m.find();
	}

判断输入字符串是否为一个有效的邮箱

	 * @param email
	 *            输入字符串
	 * @return boolean true:有效邮箱,false:无效邮箱
	 */
	public static boolean isValidEmail(String email) {
		boolean result = false;
		String regexEmail = "[a-zA-Z0-9_-][\.a-zA-Z0-9_-]*@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+";
		Pattern pattern = Pattern.compile(regexEmail);
		Matcher matcher = pattern.matcher(email);
		result = matcher.matches();
		return result;
	}

得到ip

/**
	 * 得到ip
	 * 
	 * @param request
	 * @return
	 */
	public static String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}

		// 验证ip地址是否合法
		return getLegitimateIP(ip.split(","));
	}

得到合法ip地址

/**
	 * 得到合法ip地址
	 * 
	 * @param ips
	 * @return
	 */
	public static String getLegitimateIP(String... ips) {
		Matcher matcher; // 以验证127.400.600.2为例
		if (null != ips && ips.length > 0) {
			for (String ip : ips) {
				matcher = pattern.matcher(ip);
				if (matcher.matches()) {
					return ip;
				}
			}
		}

		return "Illegal IP";
	}

从小到大排序

/**
	 * 从小到大排序
	 * 
	 * @param str
	 * @return
	 */
	public static Integer[] sort(String str) {
		String[] strs = str.split(",", 1000);
		Integer[] is = new Integer[strs.length];
		int i = 0;

		for (String s : strs) {
			if (isInteger(s)) {
				// 把字符转换成字符串
				int d = Integer.parseInt(s); // 把字符串转换成数字
				is[i] = d;
				i++;
			}
		}

		Arrays.sort(is);
		return is;
	}

获取当前系统时间转成字符串

/**
	 * 获取当前系统时间转成字符串
	 * 
	 * @author 陈运江
	 */
	public String refFormatNowDate() {
		Date nowTime = new Date(System.currentTimeMillis());
		SimpleDateFormat sdFormatter = new SimpleDateFormat("yyyyMMddHHmmss");
		String retStrFormatNowDate = sdFormatter.format(nowTime);
		return retStrFormatNowDate;
	}

取随机字符串

/**
	 * 取随机字符串
	 * 
	 * @param length
	 *            返回随机字符串的长度
	 * @param type
	 *            要取的字符串类型: i、取数字 l、取小写字母 u、取大写字母 s、取特殊字符
	 * @return String 随机字符串
	 */
	public String getRandomString(int length, String type) {
		String splitStr = " "; // 分割符
		String allStr = this.getString(type);
		String[] arrStr = allStr.split(splitStr);
		StringBuffer pstr = new StringBuffer();
		if (length > 0) {
			for (int i = 0; i < length; i++) {
				pstr.append(arrStr[new Random().nextInt(arrStr.length)]);
			}
		}
		return pstr.toString();
	}

取数字字符串 用 splitStr 分割

// 取数字字符串 用 splitStr 分割
	private String getNumberString() {
		String splitStr = " "; // 分割符

		StringBuffer buf = new StringBuffer();
		for (int i = 0; i < 10; i++) {

			buf.append(String.valueOf(i));
			buf.append(splitStr);
		}
		return buf.toString();
	}

取大写字母字符串 用 splitStr 分割

	// 取大写字母字符串 用 splitStr 分割
	private String getUppercase() {
		String splitStr = " "; // 分割符
		StringBuffer buf = new StringBuffer();
		for (int i = 0; i < 26; i++) {
			buf.append(String.valueOf((char) ('A' + i)));
			buf.append(splitStr);
		}
		return buf.toString();
	}

取小写字母字符串 用 splitStr 分割

// 取小写字母字符串 用 splitStr 分割
	private String getLowercase() {
		String splitStr = " "; // 分割符
		StringBuffer buf = new StringBuffer();
		for (int i = 0; i < 26; i++) {
			buf.append(String.valueOf((char) ('a' + i)));
			buf.append(splitStr);
		}
		return buf.toString();
	}

取特殊字符串 用 splitStr 分割

	// 取特殊字符串 用 splitStr 分割
	private String getSpecialString() {
		String splitStr = " "; // 分割符
		String str = "~@#$%^&*()_+|\=-`";
		StringBuffer buf = new StringBuffer();
		for (int i = 0; i < str.length(); i++) {
			buf.append(str.substring(i, i + 1));
			buf.append(splitStr);
		}
		return buf.toString();
	}

格式化数字保留两位小数

/**
	 * 格式化数字保留两位小数
	 * 如果是144.0或114.00 则返回114 ,如果带小数点则四舍五入到保留2位小数
	 * @param v
	 * @return
	 */
	public static String formatNum(Object  val){
		String result = "" ;
		if(val != "null" && val != null && val != ""){
			String v =  val.toString();
			if(v.indexOf(".") > -1){
				if("0".equals(v.split("\.")[1]) || "00".equals(v.split("\.")[1])){
					result =  v.split("\.")[0];
				}else{
					Double d = Double.valueOf(v);
					result = String.format("%.2f",d);
				}
			}else{
				result = v ;
			}
		} 
		
		return result;
	}

获取多少位随机数

    /**
     * 获取多少位随机数
     * @param num
     * @return
     */
    public static String getNumStringRandom(int num){
        StringBuilder str = new StringBuilder();
        Random random = new Random();
        //随机生成数字,并添加到字符串
        for(int i = 0;i<num;i++){
            str.append(random.nextInt(10));
        }
        return  str.toString();
    }

获取区间内的随机数

    /**
     * 获取区间内的随机数
     * @param min
     * @param max
     * @return
     */
    public static int getRandomBetween(int min, int max){
        Random random = new Random();
        int s = random.nextInt(max)%(max-min+1) + min;
        return s;
    }
}

随机生成字符串数组中的字符串

Random r = new Random();
String gsName[] = {"G15", "G18荣乌高速", "264省道", "302省道", "S19龙青高速"};

String gs = gsName[r.nextInt(4)];
sout('gs')
原文地址:https://www.cnblogs.com/aixing/p/13327576.html