簡體   English   中英

如何檢查字符串是否包含空格

[英]How to check whether a string contains white spaces

如何檢查字符串中是否包含空格?

使用rangeOfCharactersFromSet:

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

注意:這也會在字符串的開頭或結尾找到空格。 如果你不想首先修剪這個字符串......

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

您還可以按照以下步驟操作:

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

如果您的字符串中有任何空格,那么它將分隔這些空格並在數組中存儲不同的組件。 現在你需要計算數組。 如果count大於1,則表示存在兩個組件,即存在空白區域。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM