Conversion between strings and characters commonly used in Java notes

One, string -> character array

1. Direct transfer:

String s = "abc";
char[] cs = s.toCharArray();

2. There is a separator:
you have to set up another String type array

String[] split(String regex)
splits this string according to the match of the given regular expression.

Two, character array -> string

1. Convert all character arrays to strings

String(char[] value)
assigns a new String to represent the character sequence currently contained in the character array parameter

char[] cs ={
    
    'a','b','c'};
s = new String (cs);

or

static String valueOf(char[] data)
returns the string representation of the char array parameter.

char[] cs = {
    
     'a', 'b', 'c' };
String t = "";
System.out.println(t.valueOf(cs));

3. Part of the character array is converted into a string

String(char[] value, int offset, int count)
allocates a new String, which contains characters taken from a sub-array of the character array parameter

char[] cs ={
    
    'a','b','c'};
s = new String (cs , 0, 2);

3. Love and kill between characters and strings:

char charAt(int index)
returns the char value at the specified index.

String replace(char oldChar, char newChar)
returns a new string, which is obtained by replacing all oldChar that appears in this string with newChar.

Four, compare

static boolean equals(char[] a, char[] a2) Returns true if the two specified character arrays are equal to each other.

static boolean equals(int[] a, int[] a2) Returns true if the two specified int arrays are equal.

static boolean equals(Object[] a, Object[] a2) Returns
true if the two specified object arrays are equal to each other.

Guess you like

Origin blog.csdn.net/weixin_44998686/article/details/108098234