Skip to Main Content
Java Cookbook
book

Java Cookbook

by Ian F. Darwin
June 2001
Intermediate to advanced content levelIntermediate to advanced
888 pages
21h 1m
English
O'Reilly Media, Inc.
Content preview from Java Cookbook

Processing a String One Character at a Time

Problem

You want to process the contents of a string one character at a time.

Solution

Use a for loop and the String’s charAt( ) method.

Discussion

A string’s charAt( ) method retrieves a given character by index number (starting at zero) from within the String object. To process all the characters in a String, one after another, use a for loop ranging from zero to String.length( )-1. Here we process all the characters in a String:

// StrCharAt.java
String a = "A quick bronze fox leapt a lazy bovine";
for (int i=0; i < a.length(  ); i++)
    System.out.println("Char " + i + " is " + a.charAt(i));

A checksum is a numeric quantity representing and confirming the contents of a file. If you transmit the checksum of a file separately from the contents, a recipient can checksum the file -- assuming the algorithm is known -- and verify that the file was received intact. Example 3-3 shows the simplest possible checksum, computed just by adding the numeric value of each character together. It should produce the value “1248” if the input is “an apple a day”. Note that on files, it will not include the values of the newline characters; to fix this, retrieve System.getProperty("line.separator"); and add its character value(s) into the sum at the end of each line. Or, give up on line mode and read the file a character at a time.

Example 3-3. CheckSum.java

/** CheckSum one file, given an open BufferedReader. */ public int process(BufferedReader is) { int sum ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Practical Cloud-Native Java Development with MicroProfile

Practical Cloud-Native Java Development with MicroProfile

Emily Jiang, Andrew McCright, John Alcorn, David Chan, Alasdair Nottingham
Distributed Computing in Java 9

Distributed Computing in Java 9

Raja Malleswara Rao Malleswara Rao Pattamsetti

Publisher Resources

ISBN: 0596001703Supplemental ContentCatalog PageErrata