将两个字符串中每个字符串的所有第一个相似字符放入另一个字符串

时间:2014-08-11 20:14:29

标签: objective-c nsstring compare

在我的iOS应用程序中,我有两个NSStrings:“一二三”和“一二十”。 我需要将每个字符串的所有第一个类似的字符放入另一个NSString“one two t” 请帮忙。

1 个答案:

答案 0 :(得分:1)

NSString *firstString = @"One two three";
NSString *secondString = @"One two ten";

NSString *shorterString;
NSString *longerString;

if (firstString.length >= secondString.length) {
    shorterString = secondString;
    longerString = firstString;
} else {
    shorterString = firstString;
    longerString = secondString;
}

NSString *newString = @"";

int index = 0;

while ([[shorterString substringWithRange:NSMakeRange(index, 1)] isEqualToString: [longerString substringWithRange:NSMakeRange(index, 1)]]  && index < shorterString.length ) {
    newString = [newString stringByAppendingString:[shorterString substringWithRange:NSMakeRange(index, 1)]];
    index++;
}
NSLog(newString);