2012-04-23 22 views
0

對於我的應用程序我需要比較單詞但不是整個單詞。如果它在文字中的相同位置,我希望它能夠對一封信進行分類。所有單詞的最大長度爲6.拆分多個字符串中的標籤

兩個單詞都顯示在標籤中。

LABEL1 & LABEL2

例如,如果在LABEL1的詞是「按鈕,」我要拆,在6根弦。

string1: B 
string2: u 
string3: t 
string4: t 
string5: o 
string6: n 

然後對於我的標籤2是'磚'拆分它在6到。

string7: B 
string8: r 
string9: i 
string10: c 
string11: k 
string12: s 

現在我可以比較兩個字符串1:string7等

這樣我可以用鼠標右鍵的話中比較所有字符?我的問題是,這是否是正確的做法,以及如果代碼看起來像那樣?

我希望有人知道我的意思,並知道如何做到這一點!謝謝

回答

0

我會做這樣的事情:

- (void)findEqualsIn:(NSString *)string1 and:(NSString *)string2 { 
    for (int i = 0; i < [string1 length] && i < [string2 length]; i++) { 
     if ([string1 characterAtIndex:i] == [string2 characterAtIndex:i]) { 
      NSLog(@"%c is at index %i of both strings", [string1 characterAtIndex:i], i); 
     } 
    } 
} 

我不知道你想用它做什麼,或者你想如何返回信息(也許一個NSArray與所有匹配它的索引中?)

編輯

- (void)findEqualsIn:(NSString *)string1 and:(NSString *)string2 { 
    NSMutableArray *string1chars = [[NSMutableArray alloc] init]; 
    NSMutableArray *string2chars = [[NSMutableArray alloc] init]; 

    //filling the string1chars array 
    for (int i = 0; i < [string1 length]; i++) { 
     [string1chars addObject:[NSString stringWithFormat:@"%c", [string1 characterAtIndex:i]]]; 
    } 

    //filling the string2chars array 
    for (int i = 0; i < [string2 length]; i++) { 
     [string2chars addObject:[NSString stringWithFormat:@"%c", [string2 characterAtIndex:i]]]; 
    } 

    //checking if they have some letters in common on the same spot 
    for (int i = 0; i < [string1chars count] && i < [string2chars count]; i++) { 
     if ([[string1chars objectAtIndex:i] isEqualToString:[string2chars objectAtIndex:i]]) { 
      //change the color of the character at index i to green 
     } else { 
      //change the color of the character at index i to the standard color 
     } 
    } 
} 
+0

不應該for循環'i'比較兩個字符串的長度? '((i <[string1 length])&&((i <[string2 length]))'? – Dondragmer 2012-04-23 10:34:02

+0

你有一個有效的點,將改變這個! – Manuel 2012-04-23 10:43:55

+0

我在圖像中獲取圖像,當他們(字母)正確的地方,我希望該圖像更改爲不同顏色的相同的字母圖像,(所以另一個圖像) – Kevin 2012-04-23 11:49:34