如何搜索字符串值來查找字符串值?將字符串網址與字符串值進行比較
字符串URL:
http://localHost:8070/serviceCase=ActiveService
http://localHost:8070/serviceCase=KoplService
字符串值:
ActiveService
我需要打印確實有 「主動服務」 的網址!
如何搜索字符串值來查找字符串值?將字符串網址與字符串值進行比較
字符串URL:
http://localHost:8070/serviceCase=ActiveService
http://localHost:8070/serviceCase=KoplService
字符串值:
ActiveService
我需要打印確實有 「主動服務」 的網址!
你也許可以做這樣的事情(如果您的網址確實是一個字符串):
if ([url rangeOfString:value].location == NSNotFound){
dosomething
} else {
doSomethingElse
}
if([string hasSuffix:@"ActiveService"]) {
// Do your stuff
}
NSString *url = @"http://localHost:8070/serviceCase=ActiveService";
if ([url rangeOfString:@"ActiveService"].location != NSNotFound) {
NSLog(@"URL has the string");
}
我推薦下面的NSString類別。
NSString+Extend.h
#import <Foundation/Foundation.h>
@interface NSString (Extend)
- (BOOL)containsString:(NSString *)aString ignoringCase:(BOOL)flag;
- (BOOL)containsString:(NSString *)aString;
@end
NSString+Extend.m
#import "NSString+Extend.h"
@implementation NSString (Extend)
- (BOOL)containsString:(NSString *)aString
{
return [self containsString:aString ignoringCase:NO];
}
- (BOOL)containsString:(NSString *)aString ignoringCase:(BOOL)flag
{
unsigned mask = (flag ? NSCaseInsensitiveSearch : 0);
return [self rangeOfString:aString options:mask].length > 0;
}
@end
#import "NSString+Extend.h"
NSString *url = @"http://localHost:8070/serviceCase=ActiveService";
NSString *findString = @"ActiveService";
BOOL isContains = [url containsString:findString];
if(isContains)
{
//do stuff
}
else
{
//do stuff
}
這是一個很好的解決方案,但它確實取決於必須做字符串比較的數量。如果我們只是談論代碼中的幾個地方,我認爲你的解決方案有點矯枉過正。 – Jesper 2012-08-07 11:50:32
我知道。但是,當我測試性能比較rangeOfString沒有OverKill。當稍後使用KMP算法時,我將創建類別。 – 2012-08-07 11:55:43