objective-c - 比较具有不同顺序的字符串

标签 objective-c ios

我有一个比较字符串的 if 语句,但我想比较具有相同单词但顺序不同的字符串,并将其返回为 true。

字符串 1 a,b,c

字符串 2 b,c,a

我如何比较它们并让 if 语句将其视为相同的字符串?

最佳答案

使用 componentsSeperatedByString 分隔字符串:使用任何字符串分隔您的单词(逗号、空格)并将结果放入 NSSet。对两个字符串执行此操作并比较集合是否相等。

修改后的方法使用 mutableArray 而不是 Set 以考虑重复字符串的问题(如注释中所述):

-(BOOL) string: (NSString*) string1 isEqualTo: (NSString*) string2 {
  if (string1.length != string2.length) return NO;
  if ([string1 isEqualToString: string2]) return YES;

  NSMutableArray *array1 = [NSMutableArray arrayWithArray: [string1 componentsSeperatedByString: @","]];
  NSMutableArray *array2 = [NSMutableArray arrayWithArray: [string2 componentsSeperatedByString: @","]];

  [array1 sortUsingSelector: @selector(compare:)];
  [array2 sortUsingSelector: @selector(compare:)];

  return [array1 isEqualToArray: array2];
}

关于objective-c - 比较具有不同顺序的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10421805/

相关文章:

iphone - 获取 UITableView 中选中单元格中的值

ios - 在 UITextView Swift 3 中保存文本

objective-c - 适用于 iOS 的 GluUnProject

iphone - Objective-C/iPhone - 使用 "me/checkins"作为 Facebook Graph API 的一部分时出现 oAuthException

iphone - 展开继续问题

ios - 如何在iOS模拟器中测试强制触摸窥视和弹出?

ios - 移动 View 的背景

iphone - 使用 NSFetchedResult Controller 处理节标题

ios - 使用 unicode 字符时 NSString 中的通用字符名称错误,<

ios - 在 UIPageViewControllers 中预加载所有 UIViewControllers (Swift)