1. The mutual conversion between StringBuffer and String
1. Convert StringBuffer to String
The toString function member of the StringBuffer class can convert it to a String type.
StringBuffer buffer = newStringBuffer("abcd");String str = buffer.toString(); Convert a StringBuffer class to a String class through the construction in the String class: String(StringBuffer buffer)
StringBuffer buffer = newStringBuffer("abcd");String str = newString(buffer);2. Convert String to StringBuffer
Method 1: Use constructors
String str="Hello World.";StringBuffer buffer = new StringBuffer(str);
Method 2: Call the append function
String str="Hello World."; StringBuffer buffer = new StringBuffer();buffer.append(str);
2. The mutual conversion between String and character array
1. Convert String into a character array
The String class member toCharArray function can convert it into a character array.
String str = "Hello World.";// Create a String object char[] ch = str.toCharArray();// Then call the toCharArray function of the String object to convert it into a word
2. Convert character array to String
Method 1: Use the constructor of the String class to complete the conversion directly when constructing String.
char[] data = {'a', 'b', 'c'};String str = new String(data);Method 2: Call the valueOf function conversion of String class.
String.valueOf(char[] ch);
3. Convert StringBuffer and character array to each other
1. Convert StringBuffer to character array
Converting directly from StringBuffer to character array is not supported in Java. Instead, convert StringBuffer to String first.
Then the toCharArray function is called by String to convert it into a character array.
StringBuffer stringBuffer = new StringBuffer("Hello World.");String str = stringBuffer.toString();// First convert the StringBuffer object to String object char[] ch = str.toCharArray();// Then call the toCharArray function of the String object to convert it into a character array2. Convert character array to StringBuffer
Similar to converting a StringBuffer into a character array, you need to convert the character array into a String first, and then convert it from a String to a StringBuffer.
char[] data = {'H', 'e', 'l','l', 'o', 'd'};String str = new String();//or directly call the constructor: String str = new String(data);str = String.valueOf(data);//Calling the valueOf function of the String class to convert the character array into StringStringBuffer buffer = new StringBuffer();buffer = buffer.append(str);//Calling the append function to convert String to StringbufferSummarize
The above is the conversion between character array, String class, and StringBuffer in Java introduced to you. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support to Wulin.com website!