检查NSArray中是否包含NSString hasPrefix

时间:2013-08-02 14:38:39

标签: objective-c nsstring nsarray prefix

我有这个if语句来检查URL是否以前缀:

开头
NSString *baseUrl = @"http://example.com/";

NSString *currentURL = @"http://example.com/confirm";

if( [currentURL hasPrefix:[baseUrl stringByAppendingString:@"confirm"]] ){

    // True, so do something...

}

我想修改hasPrefix语句的if部分,以便在currentUrl附加 ANY 的值时返回true NSArray显示在此处:

NSArray *pages = [NSArray arrayWithObjects:@"confirm",@"products",nil];

我该怎么做?

4 个答案:

答案 0 :(得分:1)

只是迭代你的pages数组并设置一个布尔标志,如果存在任何术语

//
//  customstring.m
//
//  Created by rbertsch8 on 8/2/13.
//
//

#import "customstring.h"

@implementation customstring

-(bool)hasPrefixArray:(NSArray*)array withbaseURL:(NSString*)baseUrl
{
    bool hasprefix = NO;
    for(int i = 0; i < [array count] || hasprefix == NO; i++)
    {
        hasprefix = [self hasPrefix:[baseUrl stringByAppendingString:[array objectAtIndex:i]]];
    }

    return hasprefix;
}

@end

现在在您的代码中执行以下操作:     //导入自定义字符串文件     #import NSStringPrefix.h

NSStringPrefix *customURL = yoururl.com
NSString *baseUrl = baseurl.com
NSArray *yourarray = [[NSArray alloc] initWithObjects: @"one", @"two"]

if([customURL hasPrefixArray:yourarray withbaseURL:baseUrl])
{
    //dowork
}

<强>更新

在全局类中定义变量。

#define companyOrSiteName @"Company X"
#define baseUrl @"http://www.example.com/" // Set base URL for site.
#define customUrlScheme @"example://" // Set custom URL Scheme for app.
#define openInModal [NSArray arrayWithObjects: @"contact-us.php",@"products/",nil]
#define openInSafari [NSArray arrayWithObjects: @"about",@"products/resources/download",nil]
#define twitterHandle @"Example" // Twitter username without the "@" symbol
#define kTrackingId @"UA-4564564-3" // Set Google Analytics iOS App Tracking code.

答案 1 :(得分:0)

NSArray *parts = [currentUrl componentsSeparatedByString:@"/"];
NSString *name = [parts objectAtIndex:1];

在此之后,您可以检查字符串名称是否是pages数组中的元素。

答案 2 :(得分:0)

对于那些想要避免腕管综合征的人:

NSString *baseUrl = @"http://example.com/";
NSString *currentURL = @"http://example.com/confirm";
NSArray *pages = [NSArray arrayWithObjects:@"confirm",@"products",nil];
BOOL hasSuffix = NO;
[pages enumerateObjectsUsingBlock:^(NSString* page, NSUInteger idx, BOOL *stop) {
  if([currentURL hasPrefix: baseUrl] && [currentURL hasSuffix: page]){
    hasSuffix = YES;
    stop = YES;
  }
}];

您的描述听起来更像是在寻找后缀,所以您拥有它。

答案 3 :(得分:0)

很简单,请使用以下代码

BOOL hasPrefixInArray = NO;

for(int i = 0; i < [array count] && hasPrefixInArray == NO; i++)
{
    hasPrefixInArray = [yourString hasPrefix:array[i]];
}

// check value here for hasPrefixInArray
NSLog(@"%d",hasPrefixInArray);