String自定义方法

String自定义方法

    /**
     *找出字符串中有几个特定的字符串
     * @param souce 源字符串
     * @param find 指定需要查询计数字符串
     * @return 返回指定字符串的技术值
     */
public int getStrCount(String souce, String find) {
    int count = 0;
    int index = 0;
    while (true) {
        index = souce.indexOf(find, index);
        if (index > 0) {
        count++;
        index++;
        } else {
        break;
        }
    }
    return count;
 }
public static void main(String[] args) {
    String str = "aaabbbabbabc";
    String find = "ab";
    System.out.println(getStrCount(str, find));
 }

 

    /**
     *相当于String的replaceAll()方法
     * @param source 源字符串
     * @param find 需要被代替的子字符串
     * @param replacement 代替字符串
     * @return 被替换后的字符串
     */
public static String replaceAll(String source, String find, String replacement) {
    StringBuffer buffer = new StringBuffer();
    while (source.indexOf(find) != -1) {
        int index = source.indexOf(find);
        buffer.append(source.substring(0, index));
        buffer.append(replacement);
        source = source.substring(index + find.length());
    }
    buffer.append(source);
    return buffer.toString();
 }
 public static void main(String[] args) {
    String str = "aaaasdxffffwweds";
    System.out.println(replaceAll(str, "aa", "bb"));
    }

 

 

    /**字符串的replace(char oldChar, char newChar)
    * @param source 原字符串
    * @param find 查找的字符
    * @param replacewith 替代原有的字符
    */
public static String replace(String source, char find, char replacewith){
        StringBuffer buffer=new StringBuffer();
        while(source.indexOf(find)!=-1){
            int index=source.indexOf(find);
            buffer.append(source.substring(0,index));
            buffer.append(replacewith);
            source=source.substring(index+1);
        }
        buffer.append(source);
        return buffer.toString();
    }
public static void main(String[] args) {
    String str = "aaaasdxffffaaaaeds";
    System.out.println(str.replace('a', 'b'));
    }

 

 

 

//将通过分隔符分割字符串,分隔符是分割字符串的每个字符
public static String[] splitChar(String str,String stSplit)
   {
     ArrayList<String> lst = new ArrayList<String>();
     StringTokenizer st = new StringTokenizer(str,stSplit);
     while(st.hasMoreTokens())
     {
       lst.add(st.nextToken());
     }
     return (String[])lst.toArray(new String[st.countTokens()]);
   }

 

转载于:https://www.cnblogs.com/maxudong/p/8327684.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值