2011-12-05 18 views

risposta

46

uso rangeOfCharactersFromSet:

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

nota: questo sarà anche trovare spazi bianchi all'inizio o alla fine della stringa. Se non si desidera che questo assetto la stringa prima ...

NSString *trimmedString = [foo stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]; 
NSRange whiteSpaceRange = [trimmedString rangeOfCharacterFromSet:[NSCharacterSet whitespaceCharacterSet]]; 
4

Potete anche seguire questi passaggi:

NSArray *componentsSeparatedByWhiteSpace = [testString componentsSeparatedByString:@" "]; 

Se c'è qualche spazio vuoto nella stringa, allora separerà quelle e memorizzare diversi componenti nella matrice. Ora devi prendere il conteggio della matrice. Se il conteggio è maggiore di 1, significa che ci sono due componenti, cioè la presenza di uno spazio bianco.

if([componentsSeparatedByWhiteSpace count] > 1){ 
    NSLog(@"Found whitespace"); 
} 
+3

Essere consapevoli che questo è molto lento. Più lungo 'testString' è, più lento diventa rispetto al metodo' rangeOfCharacterFromSet: 'che ho usato. Poiché stamattina ero annoiato, ho confrontato le prestazioni di entrambi i metodi e ho scritto un [post di blog] (http://matthiasbauch.com/2013/05/26/stackoverflow-how-to-check-whether-a-string- contiene-spazi-bianchi /) su di esso. –

Problemi correlati