2011-03-14 243 views

回答

4

嘗試使用rangeOfString:

NSRange result = [strOne rangeOfString:strTwo]; 

從文檔:

返回NSRange結構在第一次出現aString的接收器中給出位置和長度。如果未找到aString或爲空(@""),則返回{NSNotFound, 0}

+0

謝謝!奇蹟般有效。我在下面發佈我的代碼供其他人使用。 – 2011-03-15 00:08:21

1

對於任何需要代碼檢查的字符串中存在的字符串,這是我的代碼感謝fbrereto。本實施例中檢查是否包含在字符串(字符串數組)的數組的任何字符串可以一個字符串(myString的)中找到:

int count = [stringArray count]; 

for (NSUInteger x = 0; x < count; ++x) { 

    NSRange range = [self.myString rangeOfString:[stringArray objectAtIndex:x]]; 

    if (range.length > 0) { 
     // A match has been found 
     NSLog(@"string match: %@",[stringArray objectAtIndex:x]); 
    } 
} 
+1

請注意,雖然該代碼將起作用,但更好的檢查是查看range.position!= NSNotFound(當它找不到任何內容時將返回的常量值)。 – 2011-03-15 01:57:11

1

相信這是用於檢查是否以下的範圍存在(校正響應正確的語法從肯德爾): range.location != NSNotFound

0

漸漸偏離題外話,但我總是爆炸我的琴絃,這意味着只需使用搜索字符串作爲重點爆炸它,你可以使用數組數,看看你有多少實例,。

只要有人來自使用「爆炸」將字符串吹到像我這樣的數組中的代碼語言,我發現自己寫的爆炸函數非常有用,那些不使用「爆炸」的字符串錯過了:

- (NSMutableArray *) explodeString : (NSString *)myString key:(NSString*) myKey 
{ 
    NSMutableArray *myArray = [[NSMutableArray alloc] init]; 
    NSRange nextBreak = [myString rangeOfString:myKey]; 
    while(nextBreak.location != NSNotFound) 
    { 
     [myArray addObject: [myString substringToIndex:nextBreak.location]]; 
     myString = [myString substringFromIndex:nextBreak.location + nextBreak.length]; 
     nextBreak = [myString rangeOfString:myKey]; 
    } 
    if(myString.length > 0) 
     [myArray addObject:myString]; 

    return myArray; 
} 

是這樣工作的:

[self explodeString: @"John Smith|Age: 37|Account Balance: $75.00" key:@"|"]; 

將返回這個數組:

[@"John Smith", @"Age: 37", @"Account Balance: $75.00"]; 

這可以讓你快速拉出一個特定的值在一個狹小的空間,就像如果你有一個客戶端,你想知道他有多少錢有:

[[self explodeString: clientData key: pipe] objectAtIndex: 1]; 

,或者如果你想具體的金額爲float:

[[[self explodeString: [[self explodeString: clientData key: pipe] objectAtIndex: 1] key: @": "] objectAtIndex: 2] floatValue]; 

無論如何,我發現數組的方式更容易處理和更靈活,所以這對我很有幫助。此外,您可以通過一點努力爲您的私有庫創建一個「可爆炸字符串」數據類型,以便您將其當作字符串對待或返回基於密鑰的索引值。

ExplodableString *myExplodableString; 
myExplodableString.string = @"This is an explodable|string"; 
NSString *secondValue = [myExplodableString useKey: @"|" toGetValue: index];