Objective C How to detect one or multiple spaces in a NSString

两盒软妹~` 提交于 2019-12-03 21:59:35

Im not sure whether it is the most performant way of doing it but you could split your array and see whether the length is greater than 1:

if ([string componentsSeparatedByString:@" "].count > 1)

http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html

    if( bookmarked.length == 0 )
    {
        NSLog (@"not allowed: empty");

    } 
    else if ([[bookmarked stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length] == 0)        
    { 
        NSLog (@"not allowed: whitespace(s)");
    }

    else 
    {
        [bookmarklist addObject:bookmarked];
    }
darvids0n

Depends if you're looking for ANY whitespace or just spaces. For spaces you can use:

if( [string length] == 0 ||
    !NSEqualRanges( [string rangeofString:@" "],
                    NSMakeRange(NSNotFound, 0) ) )
{
    // either the string is empty or we found a space
} else {
    // we didn't find a space and the string is at least of length 1
}

If any whitespace, use the whitespace character set:

if( [string length] == 0 ||
    !NSEqualRanges( [string rangeOfCharacterFromSet:
                     [NSCharacterSet whitespaceCharacterSet]],
                    NSMakeRange(NSNotFound, 0) ) )
{
    // either the string is empty or we found a space
} else {
    // we didn't find a space and the string is at least of length 1
}

Replace whitespaceCharacterSet with whitespaceAndNewlineCharacterSet if you like.

Look at the documentation for NSString.

Specifically, look under the section Finding Characters and Substrings for the method you want, probably you want to use – rangeOfString:options:range: multiple times.

Also, look under the section Replacing Substrings for the method you want, probably you want to use – stringByReplacingOccurrencesOfString:withString:options:range:

Take a look at the NSRegularExpression class and coding examples.

NSString *myString = @"ABC defa   jh";
int spaceCount = [[myString componentsSeparatedByString:@" "] count] - 1;

if (!spaceCount) {
    // Zero spaces, Do Something
} else if (spaceCount <= 2) {
    // 1-2 spaces add this to NSMutableArray (although the wording about what you wanted to do in each case is confusing, so adjust for your needs)
} else {
    // 3+ spaces, Do Not add this to NSMutableArray (adjust for your needs)
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!