飞道的博客

工具类篇【一】String字符串

533人阅读  评论(0)

前言

String是Java编程中最常使用的数据类型之一,或者说是java.lang包中的最常使用的元素之一,String 字符串既能作为基本数据类型存储在数据库中,又能作为大文本结构展示在前端,还能方便得跟其他数据类型(如:int、long、Double、BigDecimal等)快速转换。也能把Date转换为各种各样的格式。

一、常用方法

截取字符串方法

str原字符串

val从字符串的下标位置开始截取


  
  1. /**
  2. * @author
  3. * @DateTime 2017年12月5日 下午7:56:25
  4. *
  5. * @param str
  6. * @param val
  7. * @return
  8. */
  9. public static String subStr(String str, int val) {
  10. String returnValue = str;
  11. if (StringUtils.isNotEmpty(str) && str.length() > val) {
  12. returnValue = str.substring( 0, val);
  13. } else {
  14. returnValue = str;
  15. }
  16. return returnValue;
  17. }

截取字符串方法

str大字符串

spc要截取的包含的字符串


  
  1. public static List<String> splitString(String str, String spc) {
  2. if (str == null || str.isEmpty() || spc == null || spc.isEmpty()) {
  3. return null;
  4. }
  5. List<String> strList = new ArrayList<String>();
  6. String[] sts = str.split(spc);
  7. for (String string : sts) {
  8. strList.add(string.toString());
  9. }
  10. return strList;
  11. }

空字符串判断方法


  
  1. public static boolean isEmpty(String str) {
  2. if (str == null || str.isEmpty()) {
  3. return true;
  4. } else {
  5. return false;
  6. }
  7. }

查询某子字符(串)在母字符串中出现的次数


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

截取字符串方法

从起始位置截取到截止位置

str:字符串

beginIndex:开始的索引位置

endIndex:结束的索引位置

注意:前开后闭原则


  
  1. /**
  2. * 按起始位置截取字符串,不包含最后一位
  3. * @author
  4. * @DateTime 2019年2月21日 下午6:02:57
  5. *
  6. * @param str
  7. * @param beginIndex
  8. * @param endIndex
  9. * @return
  10. */
  11. public static String subStrByLocation(String str, int beginIndex, int endIndex) {
  12. try {
  13. return str.substring(beginIndex, endIndex);
  14. } catch (Exception e) {
  15. log.info( "",e);
  16. return "";
  17. }
  18. }

String转为int


  
  1. public static int StringToInt(String str) {
  2. try {
  3. if (str.isEmpty()) {
  4. return 0;
  5. } else {
  6. return Integer.valueOf(str);
  7. }
  8. } catch (Exception e) {
  9. log.info( "StringToInt error---->" + e);
  10. return 0;
  11. }
  12. }

 


转载:https://blog.csdn.net/Follow_24/article/details/108760876
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场