String of char in Java and deal with the problem

Transfer from: http: //blog.csdn.net/yaokai_assultmaster/article/details/52082763

In Java char is a primitive type, and String is a reference type. Sometimes we need to convert each other between them.

String converted to char

Will be converted to char in Java String is very simple.
1. String.charAt(index)(return value char) char String can be obtained in a specified location.
2. String.toCharArray()(return value char []) can be obtained through the array comprising a String char. So that we can use elements from the zero-based index position to access anywhere in the string.

char converted to a String

String to convert char approximately six ways. Summarized as follows:

String String.valueOf S = 1. ( 'C'); // most efficient method
 
2. String String.valueOf S = ( new new  char [] { 'C'}); // The char array is converted into a String
 
. 3 . Character.toString String = S ( 'C' );
 // Character.toString (char) method returns substantially directly String.valueOf (char)
 
4. String = S new new Character ( 'C' ) .toString ();

 . 5 . S String = "" + 'c' ;
 // While this method is very simple, but this is the least efficient method
 // value of the String Object in Java are immutable fact, a final variable.
// So every time we make any change to String, is to initialize a new String Object and the original variable to point to this new String.
// while the use of Java String + operator processing performed by adding method overloading.
// string added directly connected actually calls a method:
// new StringBuilder().append("").append('c').toString();


6. String s = new String(new char[]{'c'});

 

Guess you like

Origin www.cnblogs.com/doyi111/p/11492058.html