【问题标题】:splitting label in multiple strings在多个字符串中拆分标签
【发布时间】:2012-04-23 10:21:18
【问题描述】:

对于我的应用程序,我需要比较单词而不是整个单词。如果它在单词中的同一位置,我希望它重新识别一个字母。所有单词的最大长度为 6。

这两个词都显示在一个标签中。

标签1和标签2

例如,如果 label1 中的单词是“按钮”,我想将其拆分为 6 个字符串。

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

然后对于我的 label2 是 'bricks' 将它分成 6 到。

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

现在我可以比较字符串 1:string7 等。

这样我可以比较单词中的所有字符对吗?我的问题是,这是正确的做法吗?如果是这样,代码会是什么样子?

我希望有人知道我的意思并知道该怎么做!谢谢

【问题讨论】:

    标签: objective-c xcode string nsstring compare


    【解决方案1】:

    我会这样做:

    - (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
            }
        }
    }
    

    【讨论】:

    • 不应该 for 循环将i 与两个字符串长度进行比较吗? ((i &lt; [string1 length]) &amp;&amp; ((i &lt; [string2 length]))?
    • 我在 imageviews 中有图像,当它们(字母)在正确的位置时,我希望该图像更改为具有不同颜色的相同字母图像,(所以另一个图像)
    • 但我的建议是不可能的?
    • 基本上问题是我可以将带有长度为 6 的字母的标签拆分为 6 个不同的字符串/层
    • 改变我的问题或者你改变你的答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多