Java Basic Problems

Java: Break String into individual Character

In String manipulation sometimes we may need to break the string into each separate or individual character.

In java we can do it easily using  toCharArray() function.

In the given example, string   “Java Programming ”  is broken down into characters where you can see that the length of that string is 16 (including the space between  “Java” and “Programming”) and the whole string is broken into each individual character , where we have stored that characters into  an array.

Here is the code to convert  string into array:

class StringBreaker

{

StringBreaker()

{

String s=”Java Programming”;

char[] allchars=new char[s.length()];  

allchars = s.toCharArray();

System.out.println(“****************************”);

System.out.println(“\n”);

 System.out.println(“Length of S:”+s.length());

System.out.println(“\n”);

 for (int n=0; n<s.length(); n++)

{

try

            {

            System.out.println(“Character::”+(n+1)+”::”+allchars[n]);

            }

catch(Exception e){}

              }

 System.out.println(“\n”);

 System.out.println(“****************************”);

}

public static void main(String args[])

{

StringBreaker test=new StringBreaker();

}

}

OUTPUT:

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s