One of the things you may have noticed about the
String
class that is used to
represent strings in Java is that it is immutable. In other words,
there are no methods that allow you to change the contents of a
string. Methods that operate on a string return a new string, not a
modified copy of the old one. When you want to operate on a string in
place, you must use a StringBuffer
object instead.
Example 1-13
demonstrates the use of a StringBuffer
. It interactively reads a line
of user input, as Example
1-12 did, and creates a StringBuffer
to contain the line. The
program then encodes each character of the line using the
rot13 substitution cipher, which simply “rotates”
each letter 13 places through the alphabet, wrapping around from Z
back to A when necessary. Because a StringBuffer
object is being used, you can
replace each character in the line one-by-one. A session with this
Rot13Input
program might look like
this:
% java je3.basics.Rot13Input > Hello there. Testing, testing! Uryyb gurer. Grfgvat, grfgvat! > quit %
The main( )
method of Example 1-13 calls another method,
rot13( )
, to perform the actual
encoding of a character. This method demonstrates the use of the
primitive Java char
type and
character literals (i.e., characters that are used literally in a
program within single quotes).
Example 1-13. Rot13Input.java
package je3.basics; import java.io.*; // We're doing input, so import I/O classes /** * This program reads lines of text from the user, encodes them using the * trivial "Rot13" substitution cipher, and then prints out the encoded lines. **/ public class Rot13Input { public static void main(String[ ] args) throws IOException { // Get set up to read lines of text from the user BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); for(;;) { // Loop forever System.out.print("> "); // Print a prompt String line = in.readLine( ); // Read a line if ((line == null) || line.equals("quit")) // If EOF or "quit"... break; // ...break out of loop StringBuffer buf = new StringBuffer(line); // Use a StringBuffer for(int i = 0; i < buf.length( ); i++) // For each character... buf.setCharAt(i, rot13(buf.charAt(i)));// ..read, encode, store System.out.println(buf); // Print encoded line } } /** * This method performs the Rot13 substitution cipher. It "rotates" * each letter 13 places through the alphabet. Since the Latin alphabet * has 26 letters, this method both encodes and decodes. **/ public static char rot13(char c) { if ((c >= 'A') && (c <= 'Z')) { // For uppercase letters c += 13; // Rotate forward 13 if (c > 'Z') c -= 26; // And subtract 26 if necessary } if ((c >= 'a') && (c <= 'z')) { // Do the same for lowercase letters c += 13; if (c > 'z') c -= 26; } return c; // Return the modified letter } }
Get Java Examples in a Nutshell, 3rd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.