swift - 使用 readLine() 跳过行 - Swift 2.2

标签 swift swift2

我想知道当我使用 readLine() 读取包含多行的标准输入输入时是否可以跳过行。

例如标准输入

Hello
World 

是否可以不读取第一行或通过提供行号获取行而直接获取第二行?

我想做类似的事情:

getLine(1) //by line number

这是我的 hacky 解决方案

示例输入:

36
3
1 2 3
5
1 2 3 4 5
...

每隔两行阅读一次(也跳过第一行):

var lines = [String]()
var counter = -1
while let line = readLine() {
    counter+=1
    if counter == 2 {
        lines.append(line)
        counter = 0
    }
}
print(lines)

最佳答案

我写了一个快速简单的函数来获取文本索引处的一行。

func getLineOfText(lineIndex: Int, text: String) -> String?{
    let line = text.componentsSeparatedByString("\n")
    if line.count > lineIndex {
         return line[lineIndex]
    }
    else {
         return nil
    }
}

像这样使用它:

let text = "Line1 \nLine 2"
getLineOfText(1, text: text) //Returns Optional("Line 2")

或者如果你想将它用作 ant 扩展:

extension String {
    func getLineAtIndex(index: Int) -> String? {
        let lines = self.componentsSeparatedByString("\n")
        if lines.count > index {
            return lines[index]
        }
        else {
            return nil
        }
    }
}

像这样使用:

let text = "Line1 \nLine 2"
text.getLineAtIndex(1) // Returns Optional("Line 2")

关于swift - 使用 readLine() 跳过行 - Swift 2.2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36979651/

相关文章:

ios - django swift登录系统

ios - swift 2 + Xcode 7 : Sound playing when wrong button is pressed

ios - 尝试实现 uisearchcontroller 但它没有给出任何搜索结果

ios - 如何自动缩放 WKWebView 的内容?

ios - 如何将带有 Storyboard和 xib 的 swift 项目转换为自定义 sdk/框架

ios - 如何使用 swift 在 iOS 中点击谷歌地图来放置标记

swift - 在 getter setter 方法中获取警告消息 <All paths through this function will call itself>

ios - 通过内容类型为 : 'binary/octet-stream' 的 AlamofireImage 框架下载图像

ios - swift :How can i remove the outlets from code?

CocoaPods - 使用 Xcode-beta 为 iOS 9/Swift 2 构建