Swift:如何将一个字符串数组拆分成多个匹配值数组?

时间:2016-04-17 21:35:52

标签: arrays swift uitableview sorting swift2

假设我有一组值(按字母顺序排列),例如[A, B, B, B, D, G, G, H, M, M, M, M, Z]代表用户的姓氏。我正在寻找创建一个表索引,那么将像这样的数组(任意数量的用姓氏以字母表中的所有字母开头的用户)分成数组的最佳方法是什么,例如[A] [B, B, B] [D] [G, G] [H] [M, M, M, M] [Z]这似乎是是为具有多个部分的表创建值的最佳方式,其中用户以姓氏分隔。谢谢你的帮助!

4 个答案:

答案 0 :(得分:11)

您可以使用name.characters.first获取名称的首字母,并通过比较来构建数组数组:

let names = ["Aaron", "Alice", "Bob", "Charlie", "Chelsea", "David"]

var result: [[String]] = []
var prevInitial: Character? = nil
for name in names {
    let initial = name.characters.first
    if initial != prevInitial {  // We're starting a new letter
        result.append([])
        prevInitial = initial
    }
    result[result.endIndex - 1].append(name)
}

print(result)  // [["Aaron", "Alice"], ["Bob"], ["Charlie", "Chelsea"], ["David"]]

答案 1 :(得分:0)

我认为很好的方法是使用过滤器。试试这段代码:

var array = ["Aa", "Ab", "Bb", "Cc","d", "DDD"]

let A_array = array.filter({
    ($0.characters.first == "A" || $0.characters.first == "a" )
})

希望对你有帮助

答案 2 :(得分:0)

Dictionary(grouping: names) { $0.split(separator: " ").last?.first } .values

必要时排序!

答案 3 :(得分:-2)

您需要遍历原始阵列并将其重建为新阵列。这是一个例子:

$names = array ('anthony', 'bernie', 'bob', 'hank', 'mary', 'mike', 'steve', 'tom', 'tony');
$new_names = array();

foreach ($names as $name) {
  //get first letter of name
  $firstletter = substr($name, 0,1);

  //test if there is already an array for this letter
  //if not, create it
  if (!$new_names[$firstletter]) {
      $new_names[$firstletter] = array();
  }

  //add the name to the new array under the correct first letter
  array_push($new_names[$firstletter], $name);
}