2013-10-19 119 views
0

在Xcode中,我有一個if和一個else語句。if else語句混淆Objective-C

我想聲明有多個條件,但只有其中一個必須是'是'。

例如

我有一個NSString,該字符串的值是:

[NSstring stringWithFormat:@"ABCDEFG12345"]; 

我需要讓我的if語句檢查,如果A15是在串。我明白如何使用[string rangeOfString:@"CheckHere"];

我需要我的if聲明來查找給定的字母/數字中的一個或全部。如果找到一個,執行給定的代碼,如果找到兩個代碼,執行給定的代碼,如果找到三個代碼,執行給定的代碼。

+0

你的意思是,如果一至三個被發現執行相同的塊,或者如果發現執行X,如果兩個執行Y,如果三個執行Z' – Kevin

回答

6

你不需要if-else。你可以做這樣的事情。

NSString* string = @"ABCDEFG12345"; 

int foundA = [string rangeOfString:@"A"].location == NSNotFound ? 0 : 1; 
int found1 = [string rangeOfString:@"1"].location == NSNotFound ? 0 : 1; 
int found5 = [string rangeOfString:@"5"].location == NSNotFound ? 0 : 1; 

int foundCount = foundA + found1 + found5; 

switch(foundCount) { 
    case 1: [self executeOne]; break; 
    case 2: [self executeTwo]; break; 
    case 3: [self executeThree]; break; 
} 
+0

這比我的回答更完整。因爲他懶得幫助你解決問題的字符串方面,所以我懶得避開它... –

+0

@ tia-just編輯語句int foundCount = foundA + found1 + found;到int foundCount = foundA + found1 + found5; –

1

一個可行的方法:

讓我們假設你可以拼湊的(實際上有些乏味)使用rangeOfString和rangeOfCharacter調用在一起,可以寫這樣的方法:

-(NSInteger)numberOfMatchesFoundInString:(NSString*)inputString; 

這讓你傳入一個字符串,並根據找到的匹配數返回一個0,1,2 ...。

要以高度可讀的方式使用此便捷結果,可以使用switch語句。

NSInteger* matches = [self numberOfMatchesFoundInString:someString]; 
switch (matches) { 
    case 0: 
     //execute some code here for when no matches are found 
     break; 
    case 1: 
     //execute some different code when one match is found 
     break; 
    case 2: 
     //you get the idea 
     break; 

    default: 
     //some code to handle exceptions if the numberOfMatchesFoundInString method went horribly wrong 
     break; 

當然,有些人會告訴你,這是功能上並不比調用

if (someCondition) { 
    //do some stuff 
} 
else if (someOtherCondition) { 
    //do some different stuff 
} 
etc... 

不同,但說真的,你可以讓任何一個工作。

1

有幾種有用的技術可用於字符串比較。

如果你只需要測試,如果你的字符串是一個字符串列表中的一個,使用這樣的:

NSArray *options = @[@"first", @"second", @"third"]; 
if ([options contains:inputString]) { 
    // TODO: Write true block 
} else { 
    // TODO: Write else block 
} 

如果要檢查你的字符串包含從一組至少一個字符,請使用NSString -rangeOfCharacterFromSet:

不幸的是,如果你想檢查你的字符串是否包含一個或多個字符串,你別無選擇,只能寫出很長的路。如果你經常這樣做,你可以選擇編寫一個班級類別。

- (BOOL)containsAtLeastOneSubstring:(NSArray *)substrings 
{ 
    for (NSString *aString in substrings) { 
     NSRange range = [self rangeOfString:aString]; 
     if (range.location!=NSNotFound) { 
      return YES; 
     } 
    } 
    return NO; 
} 

-