Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check whether a string contains white spaces

Tags:

How to check whether a string contains whitespaces in between characters?

like image 986
Xavi Valero Avatar asked Dec 05 '11 09:12

Xavi Valero


People also ask

How do you know if a string has white spaces?

Use the test() method to check if a string contains whitespace, e.g. /\s/. test(str) . The test method will return true if the string contains at least one whitespace character and false otherwise.

How do you check if a string contains a space in C++?

The isspace() function in C++ checks if the given character is a whitespace character or not.

How do you show a space in a string?

However, " " , "\t" and "\n" are all strings containing a single character which is characterized as whitespace. If you just mean a space, use a space.

Can a string have whitespace?

In Python, string. whitespace will give the characters space, tab, linefeed, return, formfeed, and vertical tab.


1 Answers

use rangeOfCharactersFromSet:

NSString *foo = @"HALLO WELT"; NSRange whiteSpaceRange = [foo rangeOfCharacterFromSet:[NSCharacterSet whitespaceCharacterSet]]; if (whiteSpaceRange.location != NSNotFound) {     NSLog(@"Found whitespace"); } 

note: this will also find whitespace at the beginning or end of the string. If you don't want this trim the string first...

NSString *trimmedString = [foo stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]; NSRange whiteSpaceRange = [trimmedString rangeOfCharacterFromSet:[NSCharacterSet whitespaceCharacterSet]]; 
like image 126
Matthias Bauch Avatar answered Oct 21 '22 15:10

Matthias Bauch