Tools [1] String string

Preface

String is one of the most commonly used data types in Java programming, or one of the most commonly used elements in the java.lang package. String can be used as a basic data type to be stored in the database or as a large text The structure is displayed on the front end, and it can be easily converted to other data types (such as: int, long, Double, BigDecimal, etc.). It can also convert Date into various formats.

1. Common methods

Intercept string method

str original string

val is intercepted from the subscript position of the string

    /**
	 * @author 
	 * @DateTime 2017年12月5日 下午7:56:25
	 *
	 * @param str
	 * @param val
	 * @return
	 */
	public static String subStr(String str, int val) {

		String returnValue = str;
		if (StringUtils.isNotEmpty(str) && str.length() > val) {

			returnValue = str.substring(0, val);

		} else {
			returnValue = str;
		}

		return returnValue;
	}

Intercept string method

str large string

spc contains the string to be intercepted

	public static List<String> splitString(String str, String spc) {

		if (str == null || str.isEmpty() || spc == null || spc.isEmpty()) {
			return null;
		}

		List<String> strList = new ArrayList<String>();
		String[] sts = str.split(spc);

		for (String string : sts) {
			strList.add(string.toString());
		}

		return strList;
	}

Empty string judgment method

	public static boolean isEmpty(String str) {

		if (str == null || str.isEmpty()) {
			return true;
		} else {
			return false;
		}
	}

Query the number of times a sub-character (string) appears in the parent string

    /** 查证字符串出现的次数
	 *  @author 
	 *	@DateTime 2018年6月12日 上午10:53:22
	 *
	 *  @param srcText
	 *  @param findText
	 *  @return
	 */
	public static int appearNumber(String srcText, String findText) {
		int count = 0;
		int index = 0;
		while ((index = srcText.indexOf(findText, index)) != -1) {
			index = index + findText.length();
			count++;
		}
		return count;
	}

Intercept string method

Intercept from the start position to the end position

str: string

beginIndex: start index position

endIndex: end index position

Note: the principle of opening before closing and closing

	/**
	 *  按起始位置截取字符串,不包含最后一位
	 *  @author 
	 *	@DateTime 2019年2月21日 下午6:02:57
	 *
	 *  @param str
	 *  @param beginIndex
	 *  @param endIndex
	 *  @return
	 */
	public static String subStrByLocation(String str, int beginIndex, int endIndex) {

		try {
			return str.substring(beginIndex, endIndex);
		} catch (Exception e) {
			log.info("",e);
			return "";
		}
	}

String to int

	public static int StringToInt(String str) {

		try {
			if (str.isEmpty()) {
				return 0;
			} else {
				return Integer.valueOf(str);
			}
		} catch (Exception e) {
			log.info("StringToInt error---->" + e);
			return 0;
		}

	}

 

Guess you like

Origin blog.csdn.net/Follow_24/article/details/108760876