Java初级笔记No.6之Java程序实例(数组与字符串操作)

I、Java字符串

本节是一些Java中关于字符串处理的常用实例。

1.1 字符串比较
package example;
/*字符串比对*/
public class StringCompareEmp {
    public static void main(String[] args) {
        String str = "Hello World";
        String anotherStr = "hello world";
        Object objStr = str;
        
        System.out.println(str.compareTo(anotherStr));  //返回第一个不等的差值
        System.out.println(str.compareToIgnoreCase(anotherStr));    //忽略大小写
        
        System.out.println(str.compareTo(objStr.toString()));
        
    }
}

int compareTo(Object o)int compareTo(String anotherString)int compareToIgnoreCase(String str)这三个方法都是返回两个对比对象中第一个字符不等的字符差值

1.2 查找字符串最后一次出现的位置

通过字符串函数strOrig.lastIndexOf(Stringname)来查找子字符串StringnamestrOrig出现的位置:

package example;

public class SearchlastString {
    public static void main(String[] args) {
        String strOrig = "Hello world, Hello Runoob";
        String Stringname = "Runoob";
        int lastIndex = strOrig.lastIndexOf(Stringname);
        
        if (lastIndex == -1)
            System.out.println("No find " + Stringname);
        else
            System.out.println(Stringname + "last at " + lastIndex); 
    }
}

1.3 删除字符串中的一个字符

通过字符串函数substring()来删除字符串中的一个字符,并将功能封装在removeCharAt()函数中:

package example;

public class RemoveString {
    public static void main(String[] args) {
        String str = "This is Java";
        System.out.println(removeCharAt(str,3));
    }
    
    public static String removeCharAt(String s, int pos) {
        return s.substring(0,pos) + s.substring(pos+1);
    }
}
1.4 字符串替换

使用java String 类中的replace方法来替换字符串中的字符:

package example;

public class StringReplaceEmp {
    public static void main(String[] args) {
        String str = "Hello world";
        System.out.println(str.replace('H', 'W'));
        System.out.println(str.replaceFirst("He", "Wa"));
        System.out.println(str.replaceAll("He", "Ha"));
    }
}
1.5 字符串反转

使用Java的反转函数reverse()将字符串反转:

package example;

public class StringReverseEmp {
    public static void main(String[] args) {
        String string = "runoob";
        String reverse = new StringBuffer(string).reverse().toString();
        System.out.println("before reverse: " + string);
        System.out.println("after reverse " + reverse);
    }
}
1.6 字符串查找

使用String类的IndexOf()方法在字符串中查找子字符串出现的位置,如果存在返回字符串出现的位置:

package example;

public class SearchStringEmp {
    public static void main(String[] args) {
        String strOrig = "Google Runoob Taobao";
        int intIndex = strOrig.indexOf("Runoob");
        if (intIndex == -1) {
            System.out.println("no find");
        }
        else {
            System.out.println("at " + intIndex);
        }
    }
}
1.7 字符串分割

使用split()方法通过制定分隔符将字符串分割为数组:

package example;

public class StringSplitEmp {
    public static void main(String[] args) {
        String str = "www.baidu.com";
        String[] temp;
        String delimeter = "\\.";   //分隔符,  .需要进行转义
        temp = str.split(delimeter);
        
        for (int i = 0; i < temp.length; ++i) {
            System.out.println(temp[i]);
        }
    }
}

1.8 字符串小写转大写

使用String toUpperCase()方法将字符串从小写转为大写:

package example;

public class StringToUpperCaseEmp {
    public static void main(String[] args) {
        String str = "string baidu";
        String strUpper = str.toUpperCase();
        
        System.out.println("Orignal: " + str);
        System.out.println("ToUpper: " + strUpper);
    }
}
1.9 测试两个字符串区域是否相等

使用regionMatch()方法检测两个字符串区域是否相等。

package example;

public class StringRegionMatch {
    public static void main(String[] args) {
        String first = "Welcome to Microsoft";
        String second = "I work with microsoft";
        
        //表示将first第11个字符与second第12个字符开始,比较9个字符
        boolean match1 = first.regionMatches(11, second, 12, 9);    
        
        boolean match2 = first.regionMatches(true, 11, second, 12, 9);  //第一个参数true表示忽略大小写
        
        System.out.println("区分大小写的返回值: " + match1);
        System.out.println("不区分大小写的返回值: " + match2);
    }
}

1.10 字符串性能比较测试

通过两种方式创建字符串,测试其性能:

package example;

public class StringComparePerformance {
   public static void main(String[] args) {
       long startTime = System.currentTimeMillis();
       
       for (int i = 0; i < 50000; ++i) {
           String s1 = "hello";
           String s2 = "hello";
       }
       
       long endTime = System.currentTimeMillis();
       System.out.println("String关键字创建字符串 " + " : " + (endTime-startTime) + "ms");
       
       long startTime2 = System.currentTimeMillis();
       
       for (int i = 0; i < 50000; ++i) {
           String s3 = new String("hello");
           String s4 = new String("hello");
       }
       
       long endTime2 = System.currentTimeMillis();
       
       System.out.println("String对象创建字符串" + " : " + (endTime2-startTime2) + "ms");
   }
}

1.11 字符串格式化

使用format()方法来格式化字符串,还可以指定地区来格式化:

package example;

import java.util.*;

public class StringFormatEmp {
    public static void main(String[] args) {
        double e = Math.E;
        System.out.format("%f%n", e);
        System.out.format(Locale.CHINA, "%-10.4f%n%n", e);  //指定本地为中国
    }
}


1.12 连接字符串

通过+操作符和StringBuffer.append()方法来连接字符串,并比较其性能:

package example;

public class StringConcatenate {
    public static void main(String[] args) {
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < 5000; ++i) {
            String result = "This is" 
                    + "testing the" 
                    + "difference " + "between"
                    + "String" + "and" + "StringBuffer";
        }
        
        long endTime = System.currentTimeMillis();
        System.out.println("使用+ : " + (endTime-startTime) + "ms");
        
        long startTime2 = System.currentTimeMillis();
        
        for (int i = 0; i < 5000; ++i) {
            StringBuffer result = new StringBuffer();
            result.append("This is");
            result.append("testig the");
            result.append("dofference");
            result.append("between");
            result.append("String");
            result.append("and");
            result.append("StringBuffer");
        }
        
        long endTime2 = System.currentTimeMillis();
        System.out.println("StringBuffer.append(): " + (endTime2-startTime2) + "ms");
    }
}

II、数组

本节主要说明Java中对于数组的一些常用操作:

2.1 数组排序及元素查找

使用sort()方法对Java数组进行排序,使用binarySearch()方法查找数组中的元素,并使用自己定义的printArray()方法打印数组:

package example;

import java.util.Arrays;

public class SortArray {
    public static void main(String[] args) throws Exception {
        int array[] = {2,5,-2,6,-3,8,0,-7,-9,4};
        Arrays.sort(array);
        printArray("数组排序结果为: ", array);
        int index = Arrays.binarySearch(array, 2);
        System.out.println("元素2在第 " + index + " 个位置");
    }
    private static void printArray(String message, int array[]) {
        System.out.println(message + ":[length: " + array.length + "]");
        
        for (int i = 0; i < array.length; ++i) {
            if (i != 0) {
                System.out.print(", ");
            }
            System.out.print(array[i]);
        }
        System.out.println();
    }
}
2.2 数组添加元素

使用sort()方法对Java数组进行排序,使用insertElement()方法向数组插入元素:

package example;

import java.util.Arrays;

public class ArrayInsert {
    public static void main(String[] args) {
        int array[] = {2,5,-2,6,-3,8,0,-7,-9,4};
        Arrays.sort(array);
        printArray("数组排序: " , array);
        
        int index = Arrays.binarySearch(array, 1);
        System.out.println("元素1所在的位置为(负数为不存在): " + index);
        
        int newIndex = -index - 1;
        array = insertElement(array, 1, newIndex);  //需要插入位置
        printArray("数组添加元素1: " , array);
    }
    
    private static void printArray(String message, int array[]) {
        System.out.println(message + ": [length: " + array.length + "]");
        for (int i = 0; i < array.length; ++i) {
            if (i != 0)
                System.out.print(", ");
            System.out.print(array[i]);
        }
        System.out.println();
    }
    
    private static int[] insertElement(int original[], int element, int index) {
        int length = original.length;
        int destination[] = new int[length+1];
        System.arraycopy(original, 0, destination, 0, index);
        destination[index] = element;
        System.arraycopy(original, index, destination, index+1, length-index);
        
        return destination;
    }
}

2.3 获取数组长度

使用数组属性length获取数组长度。

package example;

public class ArrayLengthEmp {
    public static void main(String[] args) {
        int[][] array = { {1,2,3}, {4,5,6}, {7,8,9}, {0,5,3} };
        System.out.println(array.length);
        System.out.println(array[0].length);
    }
}

2.4 数组反转

使用Collections.reverse(ArrayList)将数组进行反转:

package example;
import java.util.ArrayList;
import java.util.Collections;

public class ArrayReverseEmp {
    public static void main(String[] args) {
        ArrayList arrayList = new ArrayList();
        arrayList.add("A");
        arrayList.add("B");
        arrayList.add("C");
        arrayList.add("D");
        arrayList.add("E");
        
        System.out.println("反转前: " + arrayList);
        Collections.reverse(arrayList);
        System.out.println("反转后: " + arrayList);
    }
}

2.5 数组后去最大和最小值

使用Collections.max()Collections.min()方法查找数组中的最大和最小值:

package example;
import java.util.Arrays;
import java.util.Collections;

public class ArrayMaxMin {
    public static void main(String[] args) {
        Integer[] numbers = {8,2,7,1,4,9,5};
        
        int min = (int)Collections.min(Arrays.asList(numbers));
        int max = (int)Collections.max(Arrays.asList(numbers));
        
        System.out.println("Max: " + max);
        System.out.println("Min: " + min);
    }
}

2.6 数组合并

通过List类的Arrays.toString()方法和List类的list.Addall(array1.asList(array2))方法将两个数组合并为一个数组:

package example;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ArrayMerge {
    public static void main(String[] args) {
        String a[] = {"A", "E", "I" };
        String b[] = {"O", "U" };
        
        List list = new ArrayList(Arrays.asList(a));
        list.addAll(Arrays.asList(b));
        Object[] c = list.toArray();
        System.out.println(Arrays.toString(c));
    }
}

2.7 数组填充

使用Arrays.fill(arrayname, value)方法和Arrays.fill(arrayname, starting index, ending index, value)方法向数组中填充元素:

package example;

import java.util.*;

public class ArrayFillEmp {
    public static void main(String[] args) {
        int array[] = new int[6];
        Arrays.fill(array, 100);
        
        for (Integer a : array)
            System.out.printf("%d,", a);
        
        System.out.println();
        
        Arrays.fill(array,  3, 6, 50);
        
        for (Integer a : array)
            System.out.printf("%d,", a);
    }
}

2.8 数组扩容

在数组初始化后对数组进行扩容:

package example;

public class ArrayExtendEmp {
    public static void main(String[] args) {
        String[] names = new String[] {"A", "B", "C"};
        String[] extended = new String[5];
        extended[3] = "D";
        extended[4] = "E";
        
        System.arraycopy(names, 0, extended, 0, names.length);
        
        for (String str : extended) {
            System.out.println(str);
        }
    }
}

2.9 删除数组元素

使用remove()方法来删除数组元素:

package example;

import java.util.ArrayList;

public class ArrayRemoveEmp {
    public static void main(String[] args) {
        ArrayList objArray = new ArrayList();
        objArray.clear();
        
        objArray.add(0,"第0个元素");
        objArray.add(1,"第1个元素");
        objArray.add(2,"第2个元素");
        
        System.out.println("Before Remove: " + objArray);
        objArray.remove(1);
        objArray.remove("第0个元素");
        System.out.println("After Remove: " + objArray);
    }
}

2.10 数组差集

使用removeAll()方法计算两个数组的差集:

package example;

import java.util.ArrayList;

public class ArrayDifferenceSetEmp {
    public static void main(String[] args) {
        ArrayList objArray = new ArrayList();
        ArrayList objArray2 = new ArrayList();
        
        objArray2.add(0,"common1");
        objArray2.add(1,"common2");
        objArray2.add(2,"notcommon");
        objArray2.add(3,"notcommon1");
        
        objArray.add(0,"common1");
        objArray.add(1,"common2");
        objArray.add(2,"notcommon2");
        
        System.out.println("array1 的元素: " + objArray);
        System.out.println("array2的元素: " + objArray2);
        
        objArray.removeAll(objArray2);
        
        System.out.println("array1与array2数组的差集为: " + objArray);
    }
}

2.11 数组交集

使用retainAll()方法计算两个数组的交集:

package example;

import java.util.ArrayList;

public class ArrayIntersectionEmp {
    public static void main(String[] args) {
        ArrayList objArray = new ArrayList();
        ArrayList objArray2 = new ArrayList();
        
        objArray2.add(0, "common1");
        objArray2.add(1, "common2");
        objArray2.add(2, "notcommon");
        objArray2.add(3, "notcommon1");
        
        objArray.add(0, "common1");
        objArray.add(1, "common2");
        objArray.add(2, "notcommon2");
        
        System.out.println("array1 数组元素: " + objArray);
        System.out.println("array2 数组元素: " + objArray2);
        
        objArray.retainAll(objArray2);
        
        System.out.println("array2 & array1: " + objArray);
    }
}

2.12 数组中查找指定元素

使用contain()方法查找数组中的指定元素:

package example;
import java.util.ArrayList;

public class ArrayContainEmp {
    public static void main(String[] args) {
        ArrayList objArray = new ArrayList();
        ArrayList objArray2 = new ArrayList();
        
        objArray2.add("common1");
        objArray2.add("common2");
        objArray2.add("notcommon");
        objArray2.add("notcommon1");
        
        objArray.add("common1");
        objArray.add("common2");
        
        System.out.println("objArray: " + objArray);
        System.out.println("objArray2: " + objArray2);
        
        System.out.println("objArray是否包含common2? " + objArray.contains("common2"));
        
        System.out.println("objArray2是否包含数组objArray? " + objArray2.contains(objArray));
    }
}

2.13 判断数组是否相等

使用equals()方法判断数组是否相等:

package example;
import java.util.Arrays;

public class ArrayEqualsEmp {
    public static void main(String[] args) {
        int[] ary = {1,2,3,4,5,6};
        int[] ary1 = {1,2,3,4,5,6};
        int[] ary2 = {1,2,3,4};
        
        System.out.println("ary == ary1 ? " + Arrays.equals(ary, ary1));
        
        System.out.println("ary1 == ary2 ? " + Arrays.equals(ary1, ary2));
    }
}
2.14 数组并集

使用union()方法计算数组并集:

package example;

import java.util.Set;
import java.util.HashSet;

public class ArrayUnionEmp {
    public static void main(String[] args) throws Exception {
        String[] arr1 = { "1", "2", "3" };
        String[] arr2 = { "4", "5", "6" };
        
        String[] result_union = union(arr1, arr2);
        
        System.out.println("Union: ");
        
        for (String str : result_union)
            System.out.println(str);
    }
    
    public static String[] union(String[] arr1, String[] arr2) {
        Set set = new HashSet();
        
        for (String str : arr1) {
            set.add(str);
        }
        
        for (String str : arr2) {
            set.add(str);
        }
        
        String[] result = {};
        return set.toArray(result);
    }
}

【参考】
[1] Java实例

你可能感兴趣的:(Java初级笔记No.6之Java程序实例(数组与字符串操作))