Saturday, February 18, 2006

Java - Stepping through Strings  [Digg.com This!]

Often we will want to step through a string a character at a time. Let's say we have a string as follows:

String mystr = new String("abcd");

We can step through each character as so:

for (int i=0; i<mystr.length(); i++)
{

}


NOTE. We use () after the length because it is a method.

~~~

To get a character at position i we use:

mystr.charAt(i)

So if we want to print out each character in turn on its own line, we would do:

for (int i=0; i<mystr.length(); i++)
{
    System.out.println("Char at " + i + " is " + mystr.charAt(i));
}


Which for mystr above, would show:

Char at 0 is a
Char at 1 is b
Char at 2 is c
Char at 3 is d


~~~

To step backwards through each character in the string, we would do:

for (int i=mystr.length()-1; i>=0; i--)
{
    System.out.println("Char at " + i + " is " + mystr.charAt(i));
}


Which for mystr above, would show:

Char at 3 is d
Char at 2 is c
Char at 1 is b
Char at 0 is a

0 Comments:

Post a Comment

<< Home