ios - 使用 Swift 从文本文件中删除单词

标签 ios swift

我正在 Swift 中使用 iOS MapKit。我获得了路线方向的表格 View 。然后我将它们保存到文本文件 (Roads.txt) 中。进入文本文件后,我想删除除道路名称之外的所有内容。这意味着我想去掉“北”、“转”、“右”等词。有没有办法在 Swift 中做到这一点,或者我必须将文件保存到数据库并在那里处理更改?

我的有效代码如下:

// Assign variables
let steps = directionsArray[indexPath.section].route.steps
let step = steps[indexPath.row] 
let instructions = step.instructions
let distance = step.distance.kilometers()

// Save Directions to text file
let directions = ["\(instructions) - \(distance),"]
let filePath = getDocumentsDirectory().stringByAppendingPathComponent("Roads.txt")
let directionstext = directions.joinWithSeparator("\n")
do {
   try directionstext.writeToFile(filePath, atomically: true, encoding: NSUTF8StringEncoding)
} catch {
 print ("Error it did not write to file")
}

//read directions from text file

let file = "Roads.txt" // read from this file
if let dir = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true).first {
    let path = NSURL(fileURLWithPath: dir).URLByAppendingPathComponent(file)
do {
    let Direc = try NSString(contentsOfURL: path, encoding: NSUTF8StringEncoding)
    print(Direc)
}
catch {print("failed to find file")}
}

最佳答案

好吧,根据上述信息,我认为有两种可能的路线(双关语)......

选项 1: 配置“后端”或信息源,以便将指令分为两半 - 方向和街道 - 这样您就可以丢弃不需要的部分创建所需文件时不需要。这将是简单而整洁的,但可能会也可能不会。

选项 2:过滤文件以删除不需要的信息。 为了演示该理论,我们假设只有两个可能的指令:“向左转”和“向右转”。然后,您可以使用以下代码从文件中删除所有指令:

let possibleInstructions = ["Turn left onto ", "Turn right onto "]
for instruction in possibleInstructions {
    direc = direc.stringByReplacingOccurrencesOfString(instruction, withString: "")
}

其中 direc 是您正在读取的文件,possibleInstructions 是该文件中可能出现的所有可能指令的数组。例如,这需要:

左转进入 Infinite Loop - 0.00,右转进入 N De Anza Blvd - 0.08,左转进入 I-280 S - 0.12,右转进入 CA-87 - 7.81,右转进入 Guadalupe Parkway S - 0.25,左转进入 CA-87 S - 0.85

并返回:

Infinite Loop - 0.00,N De Anza Blvd - 0.08,I-280 S - 0.12,CA-87 - 7.81,Guadalupe Parkway S - 0.25,进入 CA-87 S - 0.85 p>

显然,可能的指令列表会比这长得多,并且您需要额外的代码来处理特殊情况,例如“采取导出 X 合并到”,但这听起来可能对以后的工作是一个挑战流程。

关于ios - 使用 Swift 从文本文件中删除单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38502004/

相关文章:

ios - Swift:如何使用 SQLite 列填充 UITableView

iphone - 如何告诉用户最近收到的推送通知

ios - 从 UDP 服务器消息中检索字符串

iphone - 如何识别已呈现 UIViewController

swift - 使用 SKSpriteNode 的属性作为子类

swift - 核心数据 - 使用 valueForKey -OSX 将 NSManagedObject 数组更改为字符串数组

ios - 如何改变navigationItem titleView的位置

ios - 当 iPad 上的 reloadData 从非零部分变为零部分时,UITableViewController 似乎不会刷新

iphone - 即使没有与 UIViewController 关联的 Nib ,也会调用 _loadViewFromNibNamed

通过 [String : Any] and get difference to Struct or Class properties 快速循环