檢查字符串
回答
嘗試使用rangeOfString:
NSRange result = [strOne rangeOfString:strTwo];
從文檔:
返回
NSRange
結構在第一次出現aString
的接收器中給出位置和長度。如果未找到aString或爲空(@""
),則返回{NSNotFound, 0}
。
對於任何需要代碼檢查的字符串中存在的字符串,這是我的代碼感謝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]);
}
}
請注意,雖然該代碼將起作用,但更好的檢查是查看range.position!= NSNotFound(當它找不到任何內容時將返回的常量值)。 – 2011-03-15 01:57:11
相信這是用於檢查是否以下的範圍存在(校正響應正確的語法從肯德爾): range.location != NSNotFound
漸漸偏離題外話,但我總是爆炸我的琴絃,這意味着只需使用搜索字符串作爲重點爆炸它,你可以使用數組數,看看你有多少實例,。
只要有人來自使用「爆炸」將字符串吹到像我這樣的數組中的代碼語言,我發現自己寫的爆炸函數非常有用,那些不使用「爆炸」的字符串錯過了:
- (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];
- 1. 檢查字符串
- 2. 檢查字符串
- 3. 檢查字符串
- 4. 檢查字符串
- 5. 檢查字符串
- 6. 檢查字符串
- 7. 檢查字符串
- 8. 檢查字符串的子字符串
- 9. 檢查字符串包含字符串
- 10. 字母字符檢查字符串
- 11. 想法檢查字符串的某些字符的字符串檢查器?
- 12. IOS:containsObject檢查字符串
- 13. 檢查空字符串
- 14. 鏈接檢查字符串
- 15. 檢查空字符串
- 16. Java字符串檢查
- 17. 檢查字符串縮進?
- 18. 檢查字符串數組
- 19. 的JavaScript - 檢查字符串
- 20. PHP + JavaScript字符串檢查
- 21. mod_rewrite - 檢查字符串
- 22. PHP檢查空字符串
- 23. 如何檢查字符串
- 24. 字符串類型檢查
- 25. 檢查多個字符串
- 26. Javascript字符串檢查
- 27. C++檢查字符串
- 28. 檢查字符串中
- 29. 檢查字符串值
- 30. 檢查字符串函數
謝謝!奇蹟般有效。我在下面發佈我的代碼供其他人使用。 – 2011-03-15 00:08:21