删除空格,然后从字符串数组中清空行

时间:2017-12-14 14:52:59

标签: arrays swift dictionary filter whitespace

我已经将文本文件读成一个大字符串:

fileText = try NSString(contentsOfFile: pathToFile, encoding: String.Encoding.utf8.rawValue) as String

(我省略了do / catch部分,fileText在赋值之前被声明为可选的字符串常量。)

现在我将这些行拆分为一个字符串数组,修剪每个字符串的空格,然后删除所有空字符串:

let lines = (fileText!.components(separatedBy: "\n")).map { $0.trimmingCharacters(in: .whitespaces)}.filter {$0.count > 0}

它工作正常,但我正在学习Swift 4,我怀疑有更简洁的方法来完成我的任务,对吧?我很感激任何让我的代码感到羞耻的例子。谢谢!

1 个答案:

答案 0 :(得分:0)

您的代码问题,是您遍历所有String charecters四次。但任务只能迭代一次才能完成。像这样:

let myString = String() // String received from any source
var lines = [String]()
var line = ""

myString!.forEach {
   switch $0 {
   case " ":
      break
   case "\n":
      if line.count > 0 {
         lines.append(line)
         line = ""
      }
   default:
      line += String($0)
   }
}

print(lines)

对于测试文件:

$ cat test.txt 
123123123 12312312
123 12312312 12312312
sfsdfsdfsfsdf
sdfsdf 23234 sdfsdfs 23234
sdfsdf 

sdfsdfsdf

结果将是:

$ swift main.swift 
["12312312312312312", "1231231231212312312", "sfsdfsdfsfsdf", "sdfsdf23234sdfsdfs23234", "sdfsdf", "sdfsdfsdf"]