xcode 在“Swift 3”中的字符串中查找换行符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44450151/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Finding new line character in a String in "Swift 3"
提问by Mohammad Aamir
In my app I am receiving some incoming data from a web service. In that data some wrong values can also be received like new line characters. I want to find in response string that if it contains a new line character or not.
在我的应用程序中,我从 Web 服务接收一些传入数据。在该数据中,也可以接收到一些错误的值,例如换行符。我想在响应字符串中找到它是否包含换行符。
Before Swift 3I was able to do it like this
在 Swift 3 之前,我可以这样做
string.rangeOfString("\n")) == nil)
But in Swift 3this methods is no longer available. However substring
method is available which does with the help of Range
.
但在Swift 3 中,此方法不再可用。然而substring
,在 的帮助下可以使用方法Range
。
I want to detect if my string contains "\n"
how this would be accomplished using this method in Swift 3.
我想检测我的字符串是否包含"\n"
如何在Swift 3 中使用此方法来完成。
回答by Maddy
Swift 3
斯威夫特 3
string.range(of: "\n")
To check:
去检查:
if string.range(of: "\n") == nil{
}
Or if you simply want to check the string
contains \n
or not, Then,
或者,如果您只是想检查是否string
包含\n
,那么,
if !str.characters.contains("\n") {
}
回答by Nate Birkholz
If you just want to know if it is there and don't care where it is, string.contains("\n")
will return true if it is there and false if not.
如果你只是想知道它是否在那里而不关心它在哪里,string.contains("\n")
如果它在那里就返回真,否则返回假。
回答by Thibaud David
You can also use
你也可以使用
yourString.rangeOfCharacter(from: CharacterSet.newlines) != nil
which is more elegant as it's not using harcoded newline character string
这更优雅,因为它不使用硬编码的换行符字符串
回答by Lukas Kukacka
Short answer for Swift 5+
Swift 5+ 的简短回答
You can use
您可以使用
string.contains { myCharacter.isNewline
.isNewline }
to detect if string contains anynewline character.
检测字符串是否包含任何换行符。
Long answer
长答案
Swift 5 introduced couple of new properties on Character
. Those simplify such tests and are more robust then simple check for \n
.
Swift 5 在Character
. 那些简化了这样的测试并且比简单的检查更健壮\n
。
Now you can use
现在你可以使用
Character("\n").isNewline // true
Character("\r").isNewline // true
Character("a").isNewline // false
For complete list check Inspecting a Character section in Character
docs
对于完整的列表检查检查Character
文档中的字符部分
Example:
例子:
let s1 = "Hi I'm a string\n with a new line"
s1.characters.contains("\n") // => true
let s2 = "I'm not"
s2.characters.contains("\n") // => false
回答by LimeRed
.characters.contains()
should do the trick:
.characters.contains()
应该做的伎俩:
let string:String = "This is a string"
if string.range(of: "\n") == nil {
print ("contains nil")
}
else {
print("contains new line")
}
回答by elk_cloner
perferctly working in swift 3.
完美地在 swift 3 中工作。