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

Trimming Blanks from the End of a String

Problem

You need to work on a string without regard for extra leading or trailing spaces a user may have typed.

Solution

Use the String class trim( ) method.

Discussion

Example 3-8 uses trim( ) to strip an arbitrary number of leading spaces and/or tabs from lines of Java source code in order to look for the characters //+ and //-. These are special (to me) Java comments I use to mark the parts of the programs in this book that I want to include in the printed copy.

Example 3-8. GetMark.java (trimming and comparing strings)

/** the default starting mark. */
public final String startMark = "//+";
/** the default ending mark. */
public final String endMark = "//-";
/** True if we are currently inside marks. */
protected boolean printing = false;

       try {
        String inputLine;

        while ((inputLine = is.readLine(  )) != null) {
                if (inputLine.trim(  ).equals(startMark)) {
                    printing = true;
                } else if (inputLine.trim(  ).equals(endMark)) {
                    printing = false;
                } else if (printing)
                    System.out.println(inputLine);
            }
            is.close(  );
        } catch (IOException e) {
           // not shown
        }
    }
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