2014-04-08 137 views
2

如何檢查一個字符串是否包含特定的字符或單詞。 在我的情況下,我有一個字符串「紅色手冊」。在這裏,我必須檢查我的字符串中的「red ma」。 我嘗試了使用範圍的字符串方法,但它不滿足條件。如何檢查字符串是否包含字符?

這裏是我的代碼

NSString *string = @"red manual"; 
NSRange newlineRange = [string rangeOfString:@"red ma"]; 
if(newlineRange.location != NSNotFound) 
{ 
    NSLog(@"found"); 
} 
else 
{ 
    NSLog(@"not found"); 
} 
+0

可能重複? http://stackoverflow.com/questions/2753956/how-do-i-check-if-a-string-contains-another-string-in-objective-c –

+0

如果rangeOfString不起作用,則可以使用正則表達式;) –

+0

歡迎來到stackoverflow。請注意,僅僅因爲您使用'xcode IDE'並不意味着您應該使用'xcode'標籤。 'xcode'標籤保留用於與'xcode IDE'本身相關的問題,而不是您在'xcode IDE'中編寫代碼的問題。當問一個問題,如果你認爲你需要使用'xcode'標籤時,你可能根本不應該使用它。 – Popeye

回答

1

嘗試以下操作:

NSString *data = @"red manual"; 

if ([data rangeOfString:@"red ma" options:NSCaseInsensitiveSearch].location == NSNotFound) { 
    NSLog(@"not matched"); 
} 
else { 
    NSLog(@"matched"); 
} 
+0

支票的發生方式是?它是否檢查@「red ma」是否包含來自數據的任何字符,或者它檢查數據是否具有@「red ma」中的任何字符? – Supertecnoboff

+1

@Supertecnoboff:這將檢查數據是否包含@「red ma」字符串。 – astuter

+0

啊我看對了。謝謝。 – Supertecnoboff

0
NSString *string = @"red manual"; 
if([string rangeOfString:@"red ma"].location == NSNotFound) 
{ 
    NSLog(@"not found"); 
} 
else 
{ 
    NSLog(@"found"); 
} 
7
NSString *string = @"hello bla bla"; 
if ([string rangeOfString:@"bla"].location == NSNotFound) { 
    NSLog(@"string does not contain bla"); 
} else { 
    NSLog(@"string contains bla!"); 
} 

的關鍵是注意到,rangeOfString:返回NSRange struct和文件說,它returnsstruct {NSNotFound, 0}如果 「大海撈針」 不包含「針」。

如果你是在iOS 8或OS X優勝美地,你現在可以做的事:

NSString *string = @"hello bla blah"; 
if ([string containsString:@"bla"]) { 
    NSLog(@"string contains bla!"); 
} else { 
    NSLog(@"string does not contain bla"); 
} 

answered這裏

相關問題