On the conversion between java array and string
- 2021-12-04 10:13:19
- OfStack
1. char Array (Character Array)- > String
This can be done using the String. copyValueOf (charArray) function.
Examples:
char[] arr={'a','b','c'};
String string =String.copyValueOf(arr);
System.out.println(string); //abc
2. String Array- > String
String[] arr ={"0123","sb","12f"};
StringBuffer sb = new StringBuffer();
for(int i = 0;i<arr.length;i++){
sb.append(arr[i]); //append String Do not have this method, so use the StringBuffer
}
String sb1 = sb.toString();
System.out.println(sb1); //0123sb12f
3. java string- > Array
String str = "123abc";
char[] ar = str.toCharArray(); //char Array
for(int i =0;i<ar.length;i++){
System.out.println(ar[i]); //1 2 3 a b c
}
String[] arr = str.split("");
for(int i =0;i<arr.length;i++){ //String Array, but arr[0] Empty
System.out.println(arr[i]); // Empty 1 2 3 a b c
}
4. Related transformation
# # String reverse order
String s="123abc";
System.out.println(new StringBuilder(s).reverse().toString());
Strip spaces from strings
1. String. trim () trim () is to remove the first and last spaces
2. str. replace (","); Remove all spaces, including beginning and end, and copy code in the middle
String str = " hell o ";
String str2 = str.replaceAll(" ", "");
System.out.println(str2);
3. Or
replaceAll(" +",""); // Remove all spaces
4.
str = .replaceAll("\\s*", ""); replaceAll( "\n" ,""); // To clear line breaks, etc.
Replace most white space characters, not limited to spaces * can be removed
\ s can match any one of white space characters, such as spaces, tabs, page breaks, and so on
Common characters: space (''), page break ('\ f'), line break ('\ n'), carriage return ('\ r'), horizontal tab ('\ t'), vertical tab ('\ v')
Shaping and string conversion
String --
>
Int
1) int i = Integer. parseInt ([String]); Or
i = Integer.parseInt([String],[int radix]);
2) int i = Integer.valueOf(my_str).intValue();
Int-"String
1) String s = String.valueOf(i);
2) String s = Integer.toString(i);
3) String s = "" + i;
int a=33;
String a1 = String.valueOf(a); //33
String a2 = Integer.toString(a); //33
String a3 = a1 +""; //33
System.out.println(a1);
System.out.println(a2);
System.out.println(a3);
String b = "101";
String bb = "123";
int b1 = Integer.parseInt(b+bb); //101123
int b2_1 = Integer.parseInt(bb, 10); //123
int b2_2 = Integer.parseInt(b, 2); // Analytic binary system String of 5
int b3 = Integer.valueOf(b+bb).intValue(); //101123
System.out.println(b3);