14Java常用类(StringBuffer)排序算法(冒泡排序选择排序插入排序快速排序)查找算法(二分查找)

Posted ShawnYue-08

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了14Java常用类(StringBuffer)排序算法(冒泡排序选择排序插入排序快速排序)查找算法(二分查找)相关的知识,希望对你有一定的参考价值。

统计大串中小串出现的次数(新的解决方案)

class MyTest {
    public static void main(String[] args) {
        String source = "woyaoxuejava,xihuanjava,aijava,javajavawozuiai";
        String target = "java";
        int length = source.length();
        String replace = source.replace(target, "");
        int length1 = replace.length();
        int count = (length - length1) / 4;
        System.out.println(count);
    }
}
//截取字符串
class Test {
    public static void main(String[] args) {
        String str="woyaoxuejava,xihuanjava,aijava,javajavawozuiai";
        int count =0;
        int index = str.indexOf("java");
        while (index != -1) {
            count++;
            str = str.substring(index + 4);
            index = str.indexOf("java");
        }
        System.out.println(count);
    }
}

StringBuffer类

String s = "aaa" + "bbb" + "ccc";
//像这种拼串,实际上只创建一个字符串对象

StringBuffer类的概述

我们如果对字符串进行拼接操作,每次拼接,都会构建一个新的String对象,既耗时,又浪费空间。而StringBuffer就可以解决这个问题。线程安全的可变长度的字符序列

技术图片

StringBuffer的构造函数

StringBuffer() 
构造一个没有字符的字符串缓冲区,初始容量为16个字符。 
StringBuffer(int capacity) 
构造一个没有字符的字符串缓冲区和指定的初始容量。 
StringBuffer(String str) 
构造一个初始化为指定字符串内容的字符串缓冲区。 

容量在初始化完毕(构造方法执行完)后已经确定

class StringBuffer {
    public StringBuffer() {
    	super(16);
    }
    public StringBuffer(int capacity) {
        super(capacity);
    }
    public StringBuffer(String str) {
        super(str.length() + 16);
        append(str);
    }
}

abstract class AbstractStringBuilder {
    char[] value;
    int count;
    AbstractStringBuilder(int capacity) {
    	value = new char[capacity];
	}
}
package org.westos.demo;

/**
 * @author lwj
 * @date 2020/4/30 13:48
 */
public class MyTest {
    public static void main(String[] args) {
        StringBuffer s1 = new StringBuffer();
        //初始容量16个字符
        int capacity = s1.capacity();
        System.out.println(capacity);
        //16,value.length,数组理论存储的最大容量
        System.out.println(s1.length());
        //0
        //count变量,实际字符数

        StringBuffer s2 = new StringBuffer(10);
        System.out.println(s2.capacity());
        //10
        System.out.println(s2.length());
        //0

        StringBuffer s3 = new StringBuffer("Hello");
        System.out.println(s3);
        //Hello
        System.out.println(s3.capacity());
        //21
        //value = new char[str.length + 16] = new char[5 + 16] = new char[21]
        //字符数组的预设长度
        System.out.println(s3.length());
        //5
        //count,字符数组中实际存储的长度
        s3.append("World");
        System.out.println(s3.capacity());
        //21
        //5 + 5 不足以达到扩容的条件,所以capacity数组的容量不会改变

        StringBuffer s4 = new StringBuffer("Hello World, Hello Java");
        System.out.println(s4.length());
        //23
        System.out.println(s4.capacity());
        //39 = value.length + 16 = 23 + 16 = 39
        s4.append("Hello DataStructure.");
        System.out.println(s4.capacity());
        //80
        //扩容机制:int newCapacity = (value.length << 1) + 2 = 39 * 2 + 2 = 80
        System.out.println(s4.length());
        //43 > 39,必然要进行扩容
    }
}

StringBuffer的添加功能

  • public StringBuffer append
    • 可以把任意类型数据添加到字符串缓冲区里面,并返回字符串缓冲区本身
  • public StringBuffer insert
    • 在指定位置把任意类型的数据插入到字符串缓冲区里面,并返回字符串缓冲区本身

insert相比append的区别:append是在字符串后面插入,而insert是在index位置插入,在参数中需要指明要插入的位置,插入数值的类型二者一致。

package org.westos.demo;

/**
 * @author lwj
 * @date 2020/4/30 16:53
 */
public class MyDemo {
    public static void main(String[] args) {
        StringBuffer s1 = new StringBuffer("Hello");
        s1.append(1);
        //int
        s1.append(2L);
        //long
        s1.append(‘W‘);
        //char
        s1.append(3.0);
        //double
        s1.append(2.5f);
        //float
        s1.append(true);
        //boolean
        s1.append(new char[]{‘a‘, ‘b‘, ‘c‘});
        //char[]
        s1.append("ABC");
        //String
        s1.append(new StringBuffer("Java"));
        //StringBuffer
        s1.append(new Object());
        //Object
        s1.append(new char[]{‘d‘, ‘e‘, ‘f‘}, 1, 2);
        //char[], int offset, int len ef
        s1.append("ShawnYue", 1, 5);
        //String, int offset, int end hawn

        System.out.println(s1.toString());
        //Hello12W3.02.5trueabcABCJavajava.lang.Object@1b6d3586efhawn
    }
}
package org.westos.demo;

/**
 * @author lwj
 * @date 2020/4/30 16:59
 */
public class Test {
    public static void main(String[] args) {
        StringBuffer s1 = new StringBuffer("Hello");
        s1.insert(0, 1);
        //int offset, int i
        s1.insert(0, 2L);
        s1.insert(0, ‘W‘);
        s1.insert(0, 3.0);
        s1.insert(0, 2.5f);
        s1.insert(0, true);
        s1.insert(0, new char[]{‘a‘, ‘b‘, ‘c‘});
        s1.insert(0, "Java");
        s1.insert(0, new Object());
        s1.insert(0, new char[]{‘d‘, ‘e‘, ‘f‘}, 0, 3);
        s1.insert(0, "ShawnYue", 0, 8);

        System.out.println(s1.toString());
        //ShawnYuedefjava.lang.Object@1b6d3586Javaabctrue2.53.0W21Hello

        System.out.println(s1);
        //ShawnYuedefjava.lang.Object@1b6d3586Javaabctrue2.53.0W21Hello
    }
}

StringBuffer的删除功能

  • public StringBuffer deleteCharAt(int index)
    • 删除指定位置的字符,并返回本身
  • public StringBuffer delete(int start, int end)
    • 删除从指定位置开始指定位置结束的内容,并返回本身
package org.westos.demo;

/**
 * @author lwj
 * @date 2020/4/30 17:11
 */
public class Demo {
    public static void main(String[] args) {
        StringBuffer s1 = new StringBuffer("Hello World, Hello Java.");
        s1.deleteCharAt(5);
        System.out.println(s1);
        //HelloWorld, Hello Java.
        s1.deleteCharAt(11);
        System.out.println(s1);
        //HelloWorld,Hello Java.
        s1.deleteCharAt(16);
        System.out.println(s1);
        //HelloWorld,HelloJava.

        s1.delete(0, 5);
        System.out.println(s1);
        //World,HelloJava.
        //[start, end)
    }
}

StringBuffer的替换和反转功能

  • public StringBuffer replace(int start, int end, String str)
    • 从start开始到end用str替换
  • public StringBuffer reverse()
    • 字符串反转
package org.westos.demo1;

/**
 * @author lwj
 * @date 2020/4/30 17:26
 */
public class MyTest {
    public static void main(String[] args) {
        StringBuffer s1 = new StringBuffer("Hello World");
        s1.replace(0, 6, "Hi");
        System.out.println(s1);
        //HiWorld
        //[start,end)

        s1.reverse();
        System.out.println(s1);
        //dlroWiH
    }
}

StringBuffer的截取功能

  • public String substring(int start)
    • 从指定位置截取到字符串末尾
  • public String substring(int start, int end)
    • 截取从指定位置开始到结束位置,包括开始位置,不包括结束位置
package org.westos.demo1;

/**
 * @author lwj
 * @date 2020/4/30 17:31
 */
public class MyDemo {
    public static void main(String[] args) {
        StringBuffer s1 = new StringBuffer("Hello World");
        String substring = s1.substring(0);
        System.out.println(substring);
        //Hello World
        //[start, length]
        //substring的返回值类型为String

        String substring1 = s1.substring(0, 4);
        System.out.println(substring1);
        //Hell
        //[start, end)


        System.out.println(s1);
        //Hello World
        //substring不会影响原有的StringBuffer
    }
}

StringBuffer的查找功能

package org.westos.demo1;

/**
 * @author lwj
 * @date 2020/5/1 10:59
 */
public class MyDemo2 {
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer("HelloWorld,HelloJava");
        int i = sb.indexOf("Hello");
        System.out.println(i);
        //0
        //indexOf(String str)
        int j = sb.indexOf("Hello", 5);
        System.out.println(j);
        //11
        //indexOf(String str, int fromIndex)

        int m = sb.lastIndexOf("Hello");
        System.out.println(m);
        //11
        //lastIndexOf(String str)
        int n = sb.lastIndexOf("Hello", 10);
        System.out.println(n);
        //0
        //lastIndexOf(String str, int fromIndex)
    }
}

StringBuffer和String的相互转换

String ---> StringBuffer

  • new StringBuffer(String s)
  • append()方法
  • insert()方法

StringBuffer ---> String

  • toString()方法
  • substring()方法
  • new String(StringBuffer sb)
  • String.valueOf(Object)
package org.westos.demo1;

/**
 * @author lwj
 * @date 2020/4/30 17:38
 */
public class Test {
    public static void main(String[] args) {
        //String ---> StringBuffer
        StringBuffer s1 = new StringBuffer("Hello World");
        s1.append("Hello Java");
        //append的返回值类型为StringBuffer

        //StringBuffer ---> String
        String s2 = new String(s1);
        String substring = s1.substring(0);
        String s3 = s1.toString();
        String s4 = String.valueOf(s1);
        
    }
}

把数组转为字符串

需求:把数组中的数据按照指定个格式拼接成一个字符串
举例:
int[] arr = {1,2,3};	
输出结果:
"[1, 2, 3]"
package org.westos.demo1;

/**
 * @author lwj
 * @date 2020/4/30 17:40
 */
public class Demo {
    public static void main(String[] args) {
        int[] array = {1, 2, 3};
        StringBuffer s = new StringBuffer("[");
        for (int i = 0; i < array.length; i++) {
            if (i == array.length - 1) {
                s.append(array[i]).append("]");
                break;
            }
            s.append(array[i]).append(", ");
        }
        System.out.println(s.toString());
        //[1, 2, 3]
    }
}

字符串反转

需求:把字符串反转
举例:键盘录入"abc"		
输出结果:"cba"
package org.westos.demo2;

/**
 * @author lwj
 * @date 2020/4/30 17:43
 */
public class MyTest {
    public static void main(String[] args) {
        String s = "abc";
        String s1 = new StringBuffer(s).reverse().toString();
        System.out.println(s1);
        //cba
    }
}

StringBuffer和StringBuilder的区别

它们两个的API是相同的。
区别是线程安全方面。
	StringBuffer是线程安全的,效率低;
	StringBuild是线程不安全的,效率高。

String和StringBuffer分别作为参数传递

package org.westos.demo2;

/**
 * @author lwj
 * @date 2020/5/1 11:25
 */
public class MyDemo {
    public static void main(String[] args) {
        String str = "abc";
        //引用类型作为参数传递,传递的是地址
        //字符串虽然是引用类型,但是它作为参数传递的是值,不会改变值
        change(str);
        System.out.println(str);
        //abc
    }

    public static void change(String str) {
        str += "def";
        System.out.println(str);
        //abcdef
    }
}

class Demo {
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer("abc");
        change(sb);
        System.out.println(sb);
        //abcdef
    }

    public static void change(StringBuffer sb) {
        sb.append("def");
        System.out.println(sb);
        //abcdef
    }
}

数组

数组的冒泡排序

package org.westos.demo;

import java.util.Arrays;

/**
 * 冒泡排序
 * @author lwj
 * @date 2020/4/30 18:03
 */
public class BubbleSort {
    public static void main(String[] args) {
        int[] arr = {24, 69, 80, 57, 13};
        boolean flag = false;
        for (int i = 0; i < arr.length - 1; i++) {
            //外层循环控制冒泡的趟数
            for (int j = 0; j < arr.length - 1 - i; j++) {
                //内层循环来遍历交换
                if (arr[j] > arr[j + 1]) {
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                    flag = true;
                }
            }
            if (!flag) {
                break;
            }
        }
        System.out.println(Arrays.toString(arr));
        //[13, 24, 57, 69, 80]
        //优化:如果在一次遍历中没有交换,那么可以提前结束
    }
}

数组的选择排序

package org.westos.demo;

import java.util.Arrays;

/**
 * @author lwj
 * @date 2020/5/1 13:28
 */
public class SelectSort {
    public static void main(String[] args) {
        int[] arr = {24, 69, 80, 57, 13};

        for (int i = 0; i < arr.length - 1; i++) {
            int minIndex = i;
            for (int j = i + 1; j < arr.length; j++) {
                if (arr[j] < arr[minIndex]) {
                    minIndex = j;
                }
            }
            if (i != minIndex) {
                int temp = arr[minIndex];
                arr[minIndex] = arr[i];
                arr[i] = temp;
            }
        }

        System.out.println(Arrays.toString(arr));
    }
}

数组的插入排序

package org.westos.demo;

import java.util.Arrays;

/**
 * @author lwj
 * @date 2020/5/1 13:39
 */
public class InsertSort {
    public static void main(String[] args) {
        int[] arr = {24, 69, 80, 57, 13};

        for (int i = 1; i < arr.length; i++) {
            int temp = arr[i];
            int j = i;
            while (j > 0 && temp < arr[j - 1]) {
                arr[j] = arr[j - 1];
                j--;
            }
            if (i != j) {
                arr[j] = temp;
            }
        }
        System.out.println(Arrays.toString(arr));
        //[13, 24, 57, 69, 80]
    }
}

数组的快速排序

挖坑填数法完成比基准值小的放到基准值左侧,大于等于基准值的放到基准值右侧。

package org.westos.demo;

import java.util.Arrays;

/**
 * @author lwj
 * @date 2020/5/1 15:39
 */
public class QuickSort {
    public static void main(String[] args) {
        int[] arr = {24, 69, 80, 57, 13};

        ArraysUtil.quickSort(arr, 0, arr.length - 1);
        System.out.println(Arrays.toString(arr));
        //[13, 24, 57, 69, 80]
    }
}

class ArraysUtil {
    public static void quickSort(int[] arr, int start, int end) {
        if (start < end) {
            int index = getIndex(arr, start, end);
            quickSort(arr, start, index - 1);
            quickSort(arr, index + 1, end);
        }
    }

    public static int getIndex(int[] arr, int start, int end) {
        int i = start;
        int j = end;
        int pivot = arr[start];
        while (i < j) {
            while (i < j && arr[j] > pivot) {
                j--;
            }
            if (i < j) {
                arr[i] = arr[j];
                i++;
            }
            while (i < j && arr[i] < pivot) {
                i++;
            }
            if (i < j) {
                arr[j] = arr[i];
                j--;
            }
        }
        arr[i] = pivot;
        return i;
    }
}

二分查找

前提数组元素必须有序

package org.westos.demo;

/**
 * @author lwj
 * @date 2020/5/1 14:27
 */
public class BinarySearch {
    public static void main(String[] args) {
        int[] arr = {12, 21, 23, 45, 58};
        int target = 58;
        int left = 0;
        int right = arr.length - 1;
        while (left <= right) {
            int middle = (left + right) / 2;
            if (arr[middle] == target) {
                System.out.println("target在数组中的索引为" + middle);
                break;
            } else if (arr[middle] < target) {
                left = middle + 1;
            } else {
                right = middle - 1;
            }
        }
    }
}

以上是关于14Java常用类(StringBuffer)排序算法(冒泡排序选择排序插入排序快速排序)查找算法(二分查找)的主要内容,如果未能解决你的问题,请参考以下文章

Java常用类之StringBuffer与StringBuidler

2016.3.12 JAVA中StringBuffer类常用方法详解(转)

JAVA常用类_StringBuffer和StringBuilder

Java常用类--String类(StringBuilder 和 StringBuffer)介绍

Java常用类库

JAVA-基础-常用API(StringBuffer类,正则表达式)