`
龙哥IT
  • 浏览: 263859 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
文章分类
社区版块
存档分类
最新评论

字符串操作工具包

 
阅读更多
package net.oschina.app.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import java.util.regex.Pattern;

/**
 * 字符串操作工具包
 * 
 * @author liux (http://my.oschina.net/liux)
 * @version 1.0
 * @created 2012-3-21
 */
public class StringUtils {
    private final static Pattern emailer = Pattern
            .compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");

    private final static Pattern IMG_URL = Pattern
            .compile(".*?(gif|jpeg|png|jpg|bmp)");

    private final static Pattern URL = Pattern
            .compile("^(https|http)://.*?$(net|com|.com.cn|org|me|)");

    private final static ThreadLocal<SimpleDateFormat> dateFormater = new ThreadLocal<SimpleDateFormat>() {
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        }
    };

    private final static ThreadLocal<SimpleDateFormat> dateFormater2 = new ThreadLocal<SimpleDateFormat>() {
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("yyyy-MM-dd");
        }
    };

    /**
     * 将字符串转位日期类型
     * 
     * @param sdate
     * @return
     */
    public static Date toDate(String sdate) {
        return toDate(sdate, dateFormater.get());
    }

    public static Date toDate(String sdate, SimpleDateFormat dateFormater) {
        try {
            return dateFormater.parse(sdate);
        } catch (ParseException e) {
            return null;
        }
    }

    public static String getDateString(Date date) {
        return dateFormater.get().format(date);
    }

    /**
     * 以友好的方式显示时间
     * 
     * @param sdate
     * @return
     */
    public static String friendly_time(String sdate) {
        Date time = null;

        if (TimeZoneUtil.isInEasternEightZones())
            time = toDate(sdate);
        else
            time = TimeZoneUtil.transformTime(toDate(sdate),
                    TimeZone.getTimeZone("GMT+08"), TimeZone.getDefault());

        if (time == null) {
            return "Unknown";
        }
        String ftime = "";
        Calendar cal = Calendar.getInstance();

        // 判断是否是同一天
        String curDate = dateFormater2.get().format(cal.getTime());
        String paramDate = dateFormater2.get().format(time);
        if (curDate.equals(paramDate)) {
            int hour = (int) ((cal.getTimeInMillis() - time.getTime()) / 3600000);
            if (hour == 0)
                ftime = Math.max(
                        (cal.getTimeInMillis() - time.getTime()) / 60000, 1)
                        + "分钟前";
            else
                ftime = hour + "小时前";
            return ftime;
        }

        long lt = time.getTime() / 86400000;
        long ct = cal.getTimeInMillis() / 86400000;
        int days = (int) (ct - lt);
        if (days == 0) {
            int hour = (int) ((cal.getTimeInMillis() - time.getTime()) / 3600000);
            if (hour == 0)
                ftime = Math.max(
                        (cal.getTimeInMillis() - time.getTime()) / 60000, 1)
                        + "分钟前";
            else
                ftime = hour + "小时前";
        } else if (days == 1) {
            ftime = "昨天";
        } else if (days == 2) {
            ftime = "前天 ";
        } else if (days > 2 && days < 31) {
            ftime = days + "天前";
        } else if (days >= 31 && days <= 2 * 31) {
            ftime = "一个月前";
        } else if (days > 2 * 31 && days <= 3 * 31) {
            ftime = "2个月前";
        } else if (days > 3 * 31 && days <= 4 * 31) {
            ftime = "3个月前";
        } else {
            ftime = dateFormater2.get().format(time);
        }
        return ftime;
    }

    public static String friendly_time2(String sdate) {
        String res = "";
        if (isEmpty(sdate))
            return "";

        String[] weekDays = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
        String currentData = StringUtils.getDataTime("MM-dd");
        int currentDay = toInt(currentData.substring(3));
        int currentMoth = toInt(currentData.substring(0, 2));

        int sMoth = toInt(sdate.substring(5, 7));
        int sDay = toInt(sdate.substring(8, 10));
        int sYear = toInt(sdate.substring(0, 4));
        Date dt = new Date(sYear, sMoth - 1, sDay - 1);

        if (sDay == currentDay && sMoth == currentMoth) {
            res = "今天 / " + weekDays[getWeekOfDate(new Date())];
        } else if (sDay == currentDay + 1 && sMoth == currentMoth) {
            res = "昨天 / " + weekDays[(getWeekOfDate(new Date()) + 6) % 7];
        } else {
            if (sMoth < 10) {
                res = "0";
            }
            res += sMoth + "/";
            if (sDay < 10) {
                res += "0";
            }
            res += sDay + " / " + weekDays[getWeekOfDate(dt)];
        }

        return res;
    }

    /**
     * 获取当前日期是星期几<br>
     * 
     * @param dt
     * @return 当前日期是星期几
     */
    public static int getWeekOfDate(Date dt) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(dt);
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0)
            w = 0;
        return w;
    }

    /**
     * 判断给定字符串时间是否为今日
     * 
     * @param sdate
     * @return boolean
     */
    public static boolean isToday(String sdate) {
        boolean b = false;
        Date time = toDate(sdate);
        Date today = new Date();
        if (time != null) {
            String nowDate = dateFormater2.get().format(today);
            String timeDate = dateFormater2.get().format(time);
            if (nowDate.equals(timeDate)) {
                b = true;
            }
        }
        return b;
    }

    /**
     * 返回long类型的今天的日期
     * 
     * @return
     */
    public static long getToday() {
        Calendar cal = Calendar.getInstance();
        String curDate = dateFormater2.get().format(cal.getTime());
        curDate = curDate.replace("-", "");
        return Long.parseLong(curDate);
    }

    public static String getCurTimeStr() {
        Calendar cal = Calendar.getInstance();
        String curDate = dateFormater.get().format(cal.getTime());
        return curDate;
    }

    /***
     * 计算两个时间差,返回的是的秒s
     * 
     * @author 火蚁 2015-2-9 下午4:50:06
     * 
     * @return long
     * @param dete1
     * @param date2
     * @return
     */
    public static long calDateDifferent(String dete1, String date2) {

        long diff = 0;

        Date d1 = null;
        Date d2 = null;

        try {
            d1 = dateFormater.get().parse(dete1);
            d2 = dateFormater.get().parse(date2);

            // 毫秒ms
            diff = d2.getTime() - d1.getTime();

        } catch (Exception e) {
            e.printStackTrace();
        }

        return diff / 1000;
    }

    /**
     * 判断给定字符串是否空白串。 空白串是指由空格、制表符、回车符、换行符组成的字符串 若输入字符串为null或空字符串,返回true
     * 
     * @param input
     * @return boolean
     */
    public static boolean isEmpty(String input) {
        if (input == null || "".equals(input))
            return true;

        for (int i = 0; i < input.length(); i++) {
            char c = input.charAt(i);
            if (c != ' ' && c != '\t' && c != '\r' && c != '\n') {
                return false;
            }
        }
        return true;
    }

    /**
     * 判断是不是一个合法的电子邮件地址
     * 
     * @param email
     * @return
     */
    public static boolean isEmail(String email) {
        if (email == null || email.trim().length() == 0)
            return false;
        return emailer.matcher(email).matches();
    }

    /**
     * 判断一个url是否为图片url
     * 
     * @param url
     * @return
     */
    public static boolean isImgUrl(String url) {
        if (url == null || url.trim().length() == 0)
            return false;
        return IMG_URL.matcher(url).matches();
    }

    /**
     * 判断是否为一个合法的url地址
     * 
     * @param str
     * @return
     */
    public static boolean isUrl(String str) {
        if (str == null || str.trim().length() == 0)
            return false;
        return URL.matcher(str).matches();
    }

    /**
     * 字符串转整数
     * 
     * @param str
     * @param defValue
     * @return
     */
    public static int toInt(String str, int defValue) {
        try {
            return Integer.parseInt(str);
        } catch (Exception e) {
        }
        return defValue;
    }

    /**
     * 对象转整数
     * 
     * @param obj
     * @return 转换异常返回 0
     */
    public static int toInt(Object obj) {
        if (obj == null)
            return 0;
        return toInt(obj.toString(), 0);
    }

    /**
     * 对象转整数
     * 
     * @param obj
     * @return 转换异常返回 0
     */
    public static long toLong(String obj) {
        try {
            return Long.parseLong(obj);
        } catch (Exception e) {
        }
        return 0;
    }

    /**
     * 字符串转布尔值
     * 
     * @param b
     * @return 转换异常返回 false
     */
    public static boolean toBool(String b) {
        try {
            return Boolean.parseBoolean(b);
        } catch (Exception e) {
        }
        return false;
    }

    public static String getString(String s) {
        return s == null ? "" : s;
    }

    /**
     * 将一个InputStream流转换成字符串
     * 
     * @param is
     * @return
     */
    public static String toConvertString(InputStream is) {
        StringBuffer res = new StringBuffer();
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader read = new BufferedReader(isr);
        try {
            String line;
            line = read.readLine();
            while (line != null) {
                res.append(line + "<br>");
                line = read.readLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != isr) {
                    isr.close();
                    isr.close();
                }
                if (null != read) {
                    read.close();
                    read = null;
                }
                if (null != is) {
                    is.close();
                    is = null;
                }
            } catch (IOException e) {
            }
        }
        return res.toString();
    }

    /***
     * 截取字符串
     * 
     * @param start
     *            从那里开始,0算起
     * @param num
     *            截取多少个
     * @param str
     *            截取的字符串
     * @return
     */
    public static String getSubString(int start, int num, String str) {
        if (str == null) {
            return "";
        }
        int leng = str.length();
        if (start < 0) {
            start = 0;
        }
        if (start > leng) {
            start = leng;
        }
        if (num < 0) {
            num = 1;
        }
        int end = start + num;
        if (end > leng) {
            end = leng;
        }
        return str.substring(start, end);
    }

    /**
     * 获取当前时间为每年第几周
     * 
     * @return
     */
    public static int getWeekOfYear() {
        return getWeekOfYear(new Date());
    }

    /**
     * 获取当前时间为每年第几周
     * 
     * @param date
     * @return
     */
    public static int getWeekOfYear(Date date) {
        Calendar c = Calendar.getInstance();
        c.setFirstDayOfWeek(Calendar.MONDAY);
        c.setTime(date);
        int week = c.get(Calendar.WEEK_OF_YEAR) - 1;
        week = week == 0 ? 52 : week;
        return week > 0 ? week : 1;
    }

    public static int[] getCurrentDate() {
        int[] dateBundle = new int[3];
        String[] temp = getDataTime("yyyy-MM-dd").split("-");

        for (int i = 0; i < 3; i++) {
            try {
                dateBundle[i] = Integer.parseInt(temp[i]);
            } catch (Exception e) {
                dateBundle[i] = 0;
            }
        }
        return dateBundle;
    }

    /**
     * 返回当前系统时间
     */
    public static String getDataTime(String format) {
        SimpleDateFormat df = new SimpleDateFormat(format);
        return df.format(new Date());
    }

}

 

分享到:
评论

相关推荐

    字符串拼接工具

    5. **性能优化**:考虑到大规模字符串操作的性能,工具可能采用了内存效率高的算法,避免了频繁的字符串复制和内存分配。 6. **界面友好**:对于非编程人员,提供图形用户界面(GUI),使得操作更为直观和简便。 ...

    字符串转换工具

    根据提供的文件列表,"字符串转换工具 v2.5.4 Build 08.04(图).exe"很可能是这个工具的可执行文件,用户可以直接运行进行字符串转换操作。"说明.htm"则是工具的使用指南,提供了详细的使用方法和注意事项。"核客安全...

    Strings字符串分析工具

    Strings.exe是微软Windows操作系统附带的一个命令行工具,主要用于查找二进制文件中的ASCII或Unicode字符串。这个工具可以用于分析可执行文件、库文件、甚至内存转储,帮助我们识别潜在的文件名、URL、版权信息、...

    rf.rar_RF 字符串截取_Rf字符串比较_rf字符串切割

    学习和掌握RF字符串操作技巧对于任何编程者来说都是极其有价值的,因为它能够高效地处理和分析文本数据,无论是从日志文件中提取信息,还是在网页抓取中解析HTML,甚至是进行复杂的数据验证,RF都是不可或缺的工具。...

    Freemarker操作字符串

    字符串操作在FreeMarker中是通过内置的指令和函数实现的。 1. **字符串拼接**: 在FreeMarker模板中,可以使用`+`运算符来连接字符串。例如: ```html , "&gt; !"&gt; ${str1 + str2} ``` 这将输出:"Hello, World...

    MyReplace字符串替换工具

    总的来说,MyReplace字符串替换工具以其便捷的操作和强大的功能,成为处理16进制字符问题的得力助手。无论是普通用户还是专业开发人员,都能从中受益,提高文本处理的效率。通过熟练掌握这款工具,我们能够更轻松地...

    java字符串验证工具

    String 字符串操作工具类,sql防注入方法 过滤通过页面表单提交的字符 用特殊的字符连接字符串 将字符串数组转换为逗号链接的字符串,并且去掉最后一个逗号 分割字符串 字符串字符集转换 编码转换方法 将html文档...

    字符串操作类CString 类

    `CString`类是Microsoft Visual C++的一个非常重要的字符串处理类,它提供了丰富的字符串操作方法,类似于C++标准库中的`std::string`。这个类在Windows环境下被广泛使用,但描述中提到,这个版本的`CString`实现了...

    被爱可以字符串处理工具注册机

    在IT行业中,字符串处理工具是程序员和数据分析师日常工作中不可或缺的一部分。这些工具帮助用户进行文本操作,例如查找、替换、格式化、加密和解密等。"被爱可以字符串处理工具"显然是一款专为此目的设计的软件,它...

    javascript字符串操作

    ### JavaScript字符串操作详解 在JavaScript中,字符串是用于表示文本数据的一种基本数据类型。...通过本文介绍的JavaScript字符串操作方法,希望能够帮助开发者在日常工作中更加熟练地使用这些工具,提高编程效率。

    c++字符串操作

    在这个“c++字符串操作”项目中,开发者可能利用了这些工具来实现对字符串的各种操作,如字符计数、搜索、比较和修改等。下面我们将详细探讨相关的知识点。 1. **std::string 类**:这是C++标准库中的一个类,用于...

    批量字符串替换工具

    《批量字符串替换工具详解》 在日常的计算机操作中,我们常常需要对大量文本文件中的特定字符串进行查找和替换,以实现数据的统一或者格式的调整。这时,一款高效的批量字符串替换工具就显得尤为重要。本文将详细...

    广工数据结构课程设计字符串操作

    在本课程设计“广工数据结构课程设计字符串操作”中,我们将专注于一个特定的数据结构——字符串,并探讨如何对其进行高效的操作。字符串在编程中扮演着重要角色,无论是处理用户输入、文本分析还是数据存储,都离不...

    字符串操作完全演示

    在编程领域,字符串操作是日常开发中不可或缺的一部分。无论是在数据处理、用户界面交互还是算法实现中,我们都需要对字符串进行各种操作。本教程将全面介绍字符串操作的相关知识点,帮助你掌握这一重要的技能。 ...

    string字符串自动格式化单引号分隔工具

    总的来说,"string字符串自动格式化单引号分隔工具"是一个实用的辅助工具,尤其对于那些频繁进行SQL查询的数据库管理员和开发人员来说,它可以大大减少手动操作的时间和出错的可能性,从而提高工作效率。了解并熟练...

    CUDA程序并行实现字符串匹配的操作

    在这个场景下,我们将探讨如何使用CUDA在Linux环境下实现并行字符串匹配的操作。 字符串匹配是计算机科学中的一个基本问题,广泛应用于文本处理、搜索算法、生物信息学等领域。传统的串匹配算法如KMP(Knuth-Morris...

    c++ 加密字符串 工具 代码 工具一键生成

    1. 生成加密代码:使用该工具,用户可能只需要输入原始字符串和密钥,工具就会自动生成C++代码,该代码执行异或加密操作。 2. 生成解密代码:同样,工具也会生成对应的解密代码,确保能正确还原加密后的字符串。 四...

    文件字符串一键替换工具

    用户下载后,双击运行这个.exe文件,就可以启动工具并开始进行字符串替换的操作。 这类工具通常会包含以下功能: 1. 文件选择:用户可以指定需要处理的文件夹,工具会递归遍历其中的所有文件。 2. 字符串搜索与替换...

    LabVIEW删除字符串中空格

    对于更复杂的字符串操作,如删除特定类型的空白字符(如制表符、换行符),可能需要使用“替换字符串”函数。此外,如果需要处理多个字符串,可以考虑使用数组操作或循环结构。 总之,LabVIEW提供了一系列强大的...

Global site tag (gtag.js) - Google Analytics