Saturday, 12 November 2022

Check whether a string has any non-white space character or not

Write a function that takes a string as input and return true, if the string contain any non-whitespace character, else false.

 

A character is a Java whitespace character if and only if it satisfies one of the following criteria:

a.   It is a Unicode space character (SPACE_SEPARATOR, LINE_SEPARATOR, or PARAGRAPH_SEPARATOR) but is not also a non-breaking space ('\u00A0', '\u2007', '\u202F').It is '\t', U+0009 HORIZONTAL TABULATION.

b.   It is '\n', U+000A LINE FEED.

c.    It is '\u000B', U+000B VERTICAL TABULATION.

d.   It is '\f', U+000C FORM FEED.

e.   It is '\r', U+000D CARRIAGE RETURN.

f.     It is '\u001C', U+001C FILE SEPARATOR.

g.   It is '\u001D', U+001D GROUP SEPARATOR.

h.   It is '\u001E', U+001E RECORD SEPARATOR.

i.     It is '\u001F', U+001F UNIT SEPARATOR.

 

Signature

public static boolean hasNonWhitespaceChar(final String str)

 


Find the below working application.

 

StringNonWhitspaceCharCheck.java
package com.sample.app.strings;

public class StringNonWhitspaceCharCheck {

	/**
	 * 
	 * @param str
	 * 
	 * @return true if str contains any non whitespace characters, else false.
	 */
	public static boolean hasNonWhitespaceChar(final String str) {
		if (str == null || str.isEmpty()) {
			return false;
		}

		final int length = str.length();
		for (int i = 0; i < length; i++) {
			if (Character.isWhitespace(str.charAt(i))) {
				continue;
			}

			return true;
		}
		return false;
	}

	public static void main(String[] args) {
		String str1 = "\t  \n\r";
		String str2 = "\t a  \n";
		
		System.out.println("is str1 contain any non whitespace character : "+ hasNonWhitespaceChar(str1));
		System.out.println("is str2 contain any non whitespace character : "+ hasNonWhitespaceChar(str2));
	}
}

 

Output

is str1 contain any non whitespace character : false
is str2 contain any non whitespace character : true

 

References

https://docs.oracle.com/javase/8/docs/api/java/lang/Character.html

 


 

Previous                                                 Next                                                 Home

No comments:

Post a Comment