我想知道当我使用 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/