Java Trimming Blanks from the End of a String - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript Java Trimming Blanks from the End of a String - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript

Breaking

Post Top Ad

Post Top Ad

Thursday, December 27, 2018

Java Trimming Blanks from the End of a String

 Java 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. 

Explained

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 strings are special Java comments I use to mark the parts of the programs in this book that I want to include in the printed copy.


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
 }
 }

No comments:

Post a Comment

Post Top Ad