gpt4 book ai didi

swift - 如何从字符串末尾删除标志?

转载 作者:搜寻专家 更新时间:2023-10-31 22:13:11 37 4
gpt4 key购买 nike

我发现函数 String.characters.count 有一个奇怪的行为,其中行是表情符号标志:

import UIKit

var flag = "🇨🇦🇨🇦🇨🇦🇨🇦🇨🇦🇨🇦"
print(flag.characters.count)
print(flag.unicodeScalars.count)
print(flag.utf16.count)
print(flag.utf8.count)
flag = "🇨🇦0🇨🇦0🇨🇦0"
print(flag.characters.count)
print(flag.unicodeScalars.count)
print(flag.utf16.count)
print(flag.utf8.count)

enter image description here

我想在 UITextView 中编写和编辑时限制文本的字符串长度。实际上我的代码是这样的:

var lastRange: NSRange? = nil
var lastText: String? = nil

func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText string: String) -> Bool {
if string == "\n" {
// Execute same code
return false
}
var text = string.uppercaseString
if lastText != text || lastRange != nil && (lastRange!.location != range.location || lastRange!.length != range.length) {
lastRange = range
lastText = text

var text = (self.textView.text ?? "" as NSString).stringByReplacingCharactersInRange(range, withString: string)

// Delete chars if length more kMaxLengthText
while text.utf16.count >= kMaxLengthText {
text.removeAtIndex(text.endIndex.advancedBy(-1))
}
// Set position after insert text
self.textView.selectedRange = NSRange(location: range.location + lastText!.utf16.count, length: 0)
}
return false
}

最佳答案

Swift 4 (Xcode 9) 更新

从 Swift 4 开始(使用 Xcode 9 beta 测试)标志(即区域对指标)被视为一个单一的字形簇,由Unicode 9 标准。所以计算标志并删除最后一个字符(无论它是否是一个标志)现在就像:

var flags = "🇩🇪🇩🇪🇩🇪🇨🇦🇨🇦🇨🇦"
print(flags.count) // 6

flags.removeLast()
print(flags.count) // 5
print(flags) // 🇩🇪🇩🇪🇩🇪🇨🇦🇨🇦

(Swift 3 及更早版本的旧答案:)

没有错误。一系列“区域指示符”字符是单个“扩展字素簇”,这就是为什么

var flag = "🇨🇦🇨🇦🇨🇦🇨🇦🇨🇦🇨🇦"
print(flag.characters.count)

打印1(比较Swift countElements() return incorrect value when count flag emoji)。

另一方面,上面的字符串由 12 个 Unicode 标量组成(🇦🇦 是 🇦+🇦),每个都需要两个 UTF-16 码位。

要将字符串分成“可见实体”,您必须考虑“组合字符序列”,比较How to know if two emojis will be displayed as one emoji? .

我没有一个优雅的解决方案(也许有人有更好的解决方案)。但一种选择是将字符串分隔成一个数组组合字符,必要时从数组中删除元素,然后再次组合字符串。

例子:

extension String {

func composedCharacters() -> [String] {
var result: [String] = []
enumerateSubstringsInRange(characters.indices, options: .ByComposedCharacterSequences) {
(subString, _, _, _) in
if let s = subString { result.append(s) }
}
return result
}
}

var flags = "🇩🇪🇩🇪🇩🇪🇨🇦🇨🇦🇨🇦"
var chars = flags.composedCharacters()
print(chars.count) // 6
chars.removeLast()
flags = chars.joinWithSeparator("")
print(flags) // 🇩🇪🇩🇪🇩🇪🇨🇦🇨🇦

关于swift - 如何从字符串末尾删除标志?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39225534/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com