java中String类中API的实现

java String 类方法的再实现


/**
*@author StormMaybin
*@Date 2016-05-20
*/

java String 类中 trim 方法的实现:


class Function
{
    /**
    *实现字符串反转功能
    *@param String str
    *@return str
    */
    public static String reverseString(String str)
    {
        //1、字符串变数组
        char [] chs = str.toCharArray();
        //2、反转数组
        reverse(chs);
        //3、将数组变成字符串
        return new String (chs);
    }
    /**
    *实现字符串反转功能(重载)
    *@param String str,int start,int end
    *@return String
    */
    public static String reverseString(String str, int start, int end)
    {
        char [] chs = str.toCharArray();
        reverse(chs,start,end);
        return new String(chs);
    }
    /**
    *实现字符数组反转功能
    *@param char[]str
    *@return void
    */
    private static void reverse (char [] str)
    {
        for (int start = 0, end = str.length - 1; start <= end; start++, end--)
        {
            swap (str, start, end);
        }
    }
    /**
    *实现字符数组反转功能(重载)
    *@param char[] str,int start,int end
    *@return void
    */
    private static void reverse (char [] str, int start, int end)
    {
        for (end--;start <= end; start++, end--)
        {
            swap(str, start, end);
        }
    }
    /**
    *实现数组元素交换功能
    *@param char[]str,int a,int b
    *@return void
    */
    private static void swap (char [] str, int a, int b)
    {
        char temp = str[a];
        str[a] = str[b];
        str[b] = temp;
    }
}
/**
*测试类
*/
public class ReverseString 
{
    public static void main (String [] arguments)
    {
        String str = "abcdefg";
        String storm = Function.reverseString(str);
        String StormMaybin = Function.reverseString(str,0,4);
        System.out.println (storm);
        System.out.println(StormMaybin);
    }
}

用 java 实现求一个字符串中子串出现的次数:


class Function
{
    /**
    *@方法功能:计算一个字符串里面子串出现的次数
    *@param String str1, String str2
    *@return int
    */
    public static int subStringCount_1(String str1, String str2)
    {
        int count = 0;
        int index = 0;
        while ((index = str1.indexOf(str2)) != -1)
        {
            count++;
            str1 = str1.substring (index + str2.length());
        }
        return count;
    }
    /**
    *@计算子串在字符串出现的次数方法2
    *@param String str1, str2
    *@return int
    */
    public static int subStringCount_2(String str1, String str2)
    {
        int count = 0;
        int index = 0;
        while ((index = (str1.indexOf(str2,index))) != -1)
        {
            index += str2.length();
            count ++;
        }
        return count;
    }
}
/**
*测试类
*/
public class SubStringCount
{
    public static void main (String [] arguments)
    {
        String str = "abcdabcdabcdabcdhdsjdabcd";
        int count = Function.subStringCount_2(str,"abcd");
        System.out.println (count);
    }
}

你可能感兴趣的:(________JavaSE)