在 swift 中使用特殊字符分隔给定的字符串



如何在 swift 中使用特殊字符分隔给定的字符串? 例如,我想software company以下字符串分开:

I am rafiul hasan working in a "#software company#".
extension String {
func slice(from: String, to: String) -> String? {
return (range(of: from)?.upperBound).flatMap { substringFrom in
(range(of: to, range: substringFrom..<endIndex)?.lowerBound).map { substringTo in
String(self[substringFrom..<substringTo])
}
}
}
}

使用 like ->

let yourString = "I am rafiul hasan working in a #software company#."
print(yourString.slice(from: "#", to: "#"))

如果要使用某些字符分隔字符串,可以使用split(separator:)方法。 例如,如果您需要用空格分隔字符串,则可以:

let hello = "Hello World"
print(hello.split(separator: " "))
// ["Hello", "World"]

请注意,结果是[Substring],而不是[String]。如果需要字符串,可以强制转换它们:hello.split(separator: " ").map(String.init).

在您的示例中,您需要按#"分隔字符串。如果您有多个条件,则可以使用string.split(_ whereSeparator:)方法。从你的问题,

let string = "I am rafiul hasan working in a "#software company#""
print(string.split { [""", "#"].contains($0) })
// ["I am rafiul hasan working in a ", "software company"]

在您的评论中,您提到向生成的字符串添加前景色。 如果您正在处理要放置它的String,例如,UILabel,则可以仅使用textColor属性。 但是,如果您有一个长字符串,其中每个部分都需要不同的格式,则需要使用NSAttributedStringNSMutableAttributedString。这个名字说明了两者的区别。

使用您的示例,如果我想使software company具有颜色UIColor.red并且字符串的第一部分UIColor.darkGray,您可以这样做

let string = "I am rafiul hasan working in a "#software company#""
let splitted = string.split { $0 == """ || $0 == "#" }.map(String.init)
let firstAttributes: [NSAttributedString.Key: Any] = [
.foregroundColor: UIColor.darkGray
]
let firstAttributedString = NSAttributedString(
string: splitted[0],
attributes: firstAttributes)
let secondAttributes: [NSAttributedString.Key: Any] = [
.foregroundColor: UIColor.red
]
let secondAttributedString = NSAttributedString(
string: splitted[1],
attributes: secondAttributes)
let attributedString = NSMutableAttributedString(
attributedString: firstAttributedString)
attributedString.append(secondAttributedString)
// Use your attributedString to set it as `attributedText`
let label = UILabel()
label.attributedText = attributedString
...

最新更新