java-String to Array以及Array的常用操作

Java - String toCharArray() Method

This method converts this string to a new character array.
public char[] toCharArray()

Demo

import java.util.*;
public class StringToCharArray {
 
	public static void main(String[] args) {
		String testString = "This Is Test";
		char[] stringToCharArray = testString.toCharArray();
 
		for (char output : stringToCharArray) {
			System.out.println(output);
		}
	}
}

比较两个的数组是否相同

// we need to import java.util.Arrays to use Arrays.equals(). 
import java.util.Arrays; 
class Test 
{ 
	public static void main (String[] args) 
	{ 
		int arr1[] = {1, 2, 3}; 
		int arr2[] = {1, 2, 3}; 
		if (Arrays.equals(arr1, arr2)) 
			System.out.println("Same"); 
		else
			System.out.println("Not same"); 
	} 
}

output

Same

对数组进行排序的操作

 import java.util.Arrays;
 
        public class Test {
 
                /**
                 * Java比较两个数组中的元素是否相同
                 */
                public static void main(String[] args) {
                        String [] array1 = {"1","2","3"};
                        String [] array2 = {"3","2","1"};
                        Arrays.sort(array1);
                        Arrays.sort(array2);
                        if (Arrays.equals(array1, array2)) {
                                System.out.println("两个数组中的元素值相同");
                        } else {
                                System.out.println("两个数组中的元素值不相同");
                        }
                }
        }
reference

[1]String class in Java | Set 1
[2]How to compare two arrays in Java?

你可能感兴趣的:(java)