Conversion between Strings and Arrays

Strings are not arrays, but a string can be converted into an array, and vice versa. To convert a string to an array of characters, use the toCharArray method. For example, the following statement converts the string "Java" to an array.

char[] chars="Welcome to Java".toCharArray();

So chars[0] is 'J', chars[1] is 'a', chars[2] is 'v', and chars[3] is 'a' and so on...

You can also use the getChars(int srcBegin, int srcEnd, char[] dst, int dst- Begin) method to copy a substring of the string from index srcBegin to index srcEnd-1 into a character array dst starting from index dstBegin.
For example, the following code copies a substring "to java" in "Welcome to java" from index 7 to str.lenth()-1 into the character array dst starting form index 0.

import java.lang.String;
class stringtochars{
                                public static void main(String[] arg){
                                char[] chars="Welcome to Java".toCharArray();
                                for(int i=0;i<chars.length;i++)
                                System.out.print(chars[i]);
                                "Welcome to HTML".getChars(10,"Welcome to HTML".length(),chars,10);
                                for(int i=0;i<chars.length;i++)
                                System.out.print(chars[i]);
}
}

Output :  Welcome to Java
                 Welcome to HTML

Popular posts from this blog

Shutdown Pc

Ellipse using OpenGl

String Comparisons