Java中常用的几种对字符串的处理(substring,split,indexOf,lastIndexOf,replace)

1. substring

public String substring(int beginIndex, int endIndex)
返回一个新字符串,它是此字符串的一个子字符串。该子字符串从指定的 beginIndex 处开始,直到索引 endIndex - 1 处的字符。因此,该子字符串的长度为 endIndex-beginIndex。
示例:
“hamburger”.substring(4, 8) returns “urge”
“smiles”.substring(1, 5) returns “mile”
参数
beginIndex - 起始索引(包括)。
endIndex - 结束索引(不包括)。
返回
指定的子字符串。
抛出
IndexOutOfBoundsException - 如果 beginIndex 为负,或 endIndex 大于此 String 对象的长度,或 beginIndex 大于 endIndex。

public String substring(int beginIndex)
返回一个新的字符串,它是此字符串的一个子字符串。该子字符串从指定索引处的字符开始,直到此字符串末尾。
示例:

“unhappy”.substring(2) returns “happy”
“Harbison”.substring(3) returns “bison”
“emptiness”.substring(9) returns “” (an empty string)

参数
beginIndex - 起始索引(包括)。
返回
指定的子字符串。
抛出
IndexOutOfBoundsException - 如果 beginIndex 为负或大于此 String 对象的长度。

2. split

public String[] split(String regex)
将一个字符串分割为子字符串,然后将结果作为字符串数组返回。

参数
regex - 字符串或正则表达式对象,它标识了分隔字符串时使用的是一个还是多个字符。如果忽略该选项,返回包含整个字符串的单一元素数组。
返回
字符串数组,它是根据给定正则表达式的匹配拆分此字符串确定的
抛出
PatternSyntaxException - 如果正则表达式的语法无效

public String[] split(String regex,int limit)
将一个字符串分割为子字符串,然后将结果作为字符串数组返回。

参数
regex -字符串或正则表达式对象,它标识了分隔字符串时使用的是一个还是多个字符。如果忽略该选项,返回包含整个字符串的单一元素数组。
limit - 该值用来限制返回数组中的元素个数(也就是最多分割成几个数组元素,只有为正数时有影响)
返回
字符串数组,它是根据给定正则表达式的匹配拆分此字符串确定的
抛出
PatternSyntaxException - 如果正则表达式的语法无效

3. indexOf

public int indexOf(String str)
返回指定子字符串在此字符串中第一次出现处的索引。返回的整数是 this.startsWith(str, k)为 true 的最小 k 值。

参数
str - 任意字符串。
返回
如果字符串参数作为一个子字符串在此对象中出现,则返回第一个这种子字符串的第一个字符的索引;如果它不作为一个子字符串出现,则返回 -1。

public int indexOf(String str, int fromIndex)
返回指定子字符串在此字符串中第一次出现处的索引,从指定的索引开始。
返回的整数是满足下式的最小 k 值: k >= Math.min(fromIndex, this.length()) && this.startsWith(str, k)
如果不存在这样的 k 值,则返回 -1。

参数
str - 要搜索的子字符串。
fromIndex - 开始搜索的索引位置。
返回
指定子字符串在此字符串中第一次出现处的索引,从指定的索引开始。

4. lastIndexOf

public int lastIndexOf(String str)
返回指定子字符串在此字符串中最右边出现处的索引。将最右边的空字符串 “” 视为出现在索引值 this.length() 处。返回的索引是 this.startsWith(str, k) 为 true 的最大 k 值。

参数
str - 要搜索的子字符串。
返回
如果字符串参数作为一个子字符串在此对象中出现一次或多次,则返回最后一个这种子字符串的第一个字符。如果它不作为一个子字符串出现,则返回 -1。

public int lastIndexOf(String str, int fromIndex)
返回指定子字符串在此字符串中最后一次出现处的索引,从指定的索引开始反向搜索。返回的整数是满足下式的最大 k 值: k <= Math.min(fromIndex,this.length()) && this.startsWith(str, k) 如果不存在这样的 k 值,则返回 -1。

参数
str - 要搜索的子字符串。
fromIndex - 开始搜索的索引位置。
返回
指定子字符串在此字符串中最后一次出现处的索引。

5. replace

public String replace(char oldChar, char newChar)
返回一个新的字符串,它是通过用 newChar 替换此字符串中出现的所有 oldChar 得到的。 如果 oldChar 在此 String 对象表示的字符序列中没有出现,则返回对此 String 对象的引用。否则,创建一个新的 String 对象,它所表示的字符序列除了所有的 oldChar 都被替换为 newChar 之外,与此 String 对象表示的字符序列相同。

参数
oldChar - 原字符。
newChar - 新字符。
返回
一个从此字符串派生的字符串,它将此字符串中的所有 oldChar 替代为 newChar。

6. trim

public String trim()
返回字符串的副本,忽略前导空白和尾部空白。 如果此 String 对象表示一个空字符序列,或者此 String 对象表示的字符序列的第一个和最后一个字符的代码都大于 ‘\u0020’(空格字符),则返回对此 String 对象的引用。
否则,若字符串中没有代码大于 ‘\u0020’ 的字符,则创建并返回一个表示空字符串的新 String 对象。
否则,假定 k 为字符串中代码大于 ‘\u0020’ 的第一个字符的索引,m 为字符串中代码大于 ‘\u0020’ 的最后一个字符的索引。创建一个新的 String 对象,它表示此字符串中从索引 k 处的字符开始,到索引 m 处的字符结束的子字符串,即 this.substring(k, m+1) 的结果。

此方法可用于截去字符串开头和末尾的空白(如上所述)。

返回
此字符串移除了前导和尾部空白的副本;如果没有前导和尾部空白,则返回此字符串。


下面给出整体一个例子:

package test;

/**
 * 定时自备份的pojo类
 * 
 * @author CheerForU
 *
 */
public class SelfBackup {

    private int enable;
    private String month;
    private String day;
    private String week;
    private String hour;
    private String minute;

    public SelfBackup() {

    }

    public SelfBackup(final int enable, final String month, final String day, 
    final String week, final String hour,final String minute) {
        super();
        this.enable = enable;
        this.month = month;
        this.day = day;
        this.week = week;
        this.hour = hour;
        this.minute = minute;
    }
    //省略set、get方法

    @Override
    public String toString() {
        return "SelfBackup [enable=" + enable + ", month=" + month + ", day=" + day + ",
         week=" + week + ", hour="+ hour + ", minute=" + minute + "]";
    }
}

package test;

import org.apache.log4j.Logger;

public class test {

    Logger log = Logger.getLogger(test.class);

    /**
     * 获取自备份配置
     * 
     * @return
     */
    public SelfBackup getSelfBackupConfig() {

        SelfBackup selfbackup = null;

        // 实际定时配置从文件/var/spool/cron/root中读取,此处写死
        // 定时任务参数分别为:分钟,小时,几号,月份,星期几,命令。
        String allStr = "0 1 * * * /backup/bin/bkdata.sh";

        //去除空格
        final String str = allStr.trim();
        final String[] s = str.split(" ");
        final String month = trans2Num("month", s[3]);
        final String day = trans2Num("day", s[2]);
        final String week = trans2Num("week", s[4]);
        final String hour = trans2Num("hour", s[1]);
        final String minute = trans2Num("minute", s[0]);

        selfbackup = new SelfBackup(1, month, day, week, hour, minute);
        return selfbackup;
    }

    private String trans2Num(final String name, final String string) {
        if (string.equals("*")) {
            return "-1";
        } else if (!(name.equals("week")) && string.length() == 1) {
            return "0" + string;
        } else {
            return string;
        }
    }

    /**
     * 更新自备份配置
     * 
     * @return
     * @throws Exception
     */
    public synchronized boolean setSelfBackupConfig(final SelfBackup selfbackup) throws Exception {
        try {
            // 先删除定时任务配置
            final String[] delCommand = { "/bin/sh", "-c", "sed -i '/bkdata.sh/d' /var/spool/cron/root" };
            final Process delProc = Runtime.getRuntime().exec(delCommand);
            final String delRes = String.valueOf(delProc.waitFor());
            if (!(delRes.equals("0"))) {
                return false;
            }

            // 定时备份是否开启
            final String enable = String.valueOf(selfbackup.getEnable());
            if (enable.equals("0")) {
                return true;
            }
            final String month = trans2Str(selfbackup.getMonth());
            final String day = trans2Str(selfbackup.getDay());
            final String week = trans2Str(selfbackup.getWeek());
            final String hour = trans2Str(selfbackup.getHour());
            final String minute = trans2Str(selfbackup.getMinute());

            // 写出定时备份配置的格式
            String addStr = "sed -i '/sh/a\\{} {} {} {} {} /backup/bin/bkdata.sh{}' /var/spool/cron/root";

            // 替换时间参数
            addStr = replace(addStr, minute, hour, day, month, week);

            // 写入配置文件
            final String[] addCommand = { "/bin/sh", "-c", addStr };
            final Process addProc = Runtime.getRuntime().exec(addCommand);
            final String addRes = String.valueOf(addProc.waitFor());

            if (!(addRes.equals("0"))) {
                return false;
            }
            return true;
        } catch (final Exception e) {
            log.error(e.getLocalizedMessage(), e);
            throw new Exception(e);
        }
    }

    private String trans2Str(final String num) {
        if (num.equals("-1")) {
            return "*";
        } else if (num.length() == 2 && num.substring(0, 1).equals("0")) {
            return num.substring(1, 2);
        } else {
            return num;
        }
    }

    private String replace(final String addStr, final String... args) {
        int i = 0;
        final StringBuffer addBuffer = new StringBuffer(addStr);
        int index = -1;
        while (args != null && i < args.length && ((index = addBuffer.indexOf("{}")) != -1)) {
            addBuffer.replace(index, index + 2, args[i]);
            i++;
        }
        return addBuffer.toString();
    }

    public static void main(String[] args) {

        test t = new test();
        SelfBackup selfBackup = t.getSelfBackupConfig();
        System.out.println(selfBackup.toString());
        //输出结果:SelfBackup [enable=1, month=-1, day=-1, week=-1, hour=01, minute=00]
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值