Example: String reverse
The following program reverses a string in a very straightforward,
but rather inefficient way. When you learn about StringBuilder
(or the equivalent StringBuffer
), you can do this more efficiently.
But the purpose of this is to see how looping over a string works.
Nested loops. There are two nested loops in the is program, the
outer while
loop reads more input.
The inner for
loop gets every character from the input string starting at
character 0.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
// File : loops/reverse/Reverse.java // Purpose: Reverse a string using a loop. // Author : Fred Swartz // Date : Oct 23 2005 // Comments: Building a String one character at a time // is very inefficient because it requires // creating a new object for each concatenation. // StringBuilder is better, and it already // has a reverse() method! import javax.swing.*; public class Reverse { public static void main(String[] args) { String input; // Used for the input string. String reversed; // Reversed form or the input string. while (true) { input = JOptionPane.showInputDialog(null, "Enter a string"); if (input == null) break; reversed = ""; for (int i=0; i<input.length(); i++) { reversed = input.substring(i, i+1) + reversed; } JOptionPane.showMessageDialog(null, "Reversed:\n" + reversed); } } } |
While loop vs For loop
Counting. A for
loop is preferred to a while
loop when
counting through a series of numbers -- in this case all character
positions in a string.
Equivalent. A for
loop has the same condition as the equivalent while
loop, but also incorporates an initialization, which would be before the
while
statement, and the increment, which would be at
the end of the while
body. You can write the loop either way, but
putting the initialization, condition, and increment in one statement increases
the readability.
For loop | While loop |
---|---|
for (int i=0; i<input.length(); i++) { reversed = input.substring(i, i+1) + reversed; } |
int i = 0; while (i<input.length()) { reversed = input.substring(i, i+1) + reversed; i++; } |
A single character - String or char?
This program uses substring(...)
to get a single character.
It would be more efficient to use charAt(...)
, which returns
a single primitive char
value.
for (int i=0; i<input.length(); i++) { reversed = input.charAt(i) + reversed; }