自动更正 swift (IOS) 中的字符串

Autocorrect a string in swift (IOS)

我是 Whosebug 的新手,也是 IOS 中开发的新手。 我的第一个应用程序的某些部分通过 IOS 语音识别对字符串中的单个单词进行校正。 不幸的是,由于这些是单个单词或句子片段,语音识别的行为就像一个新句子,并将第一个单词大写。 有没有办法通过自动更正发送最终更正后的字符串(可以包含几个句子)?以便根据国家规范更正这些简单的错误,例如句子中间的大写(在德语中,名词和名称在句子中间也大写)。

谢谢

我相信 has the answer you're looking for but NOTE it will ignore proper nouns and other words that should be capitalized. You might be able to get what you're looking for by using this as well as UITextChecker. It's a bit old and doesn't have any answers updated for newer versions of Swift, so I went ahead and updated the syntax from :

extension String {

func toUppercaseAtSentenceBoundary() -> String {

 var result = ""
    self.uppercased().enumerateSubstrings(in: self.startIndex..<self.endIndex, options: .bySentences) { (sub, _, _, _)  in
        result += String(sub!.prefix(1))
        result += String(sub!.dropFirst(1)).lowercased()
    }

    return result as String
  }
}

// Example usage
var str = "this Is my String."
print(str.toUppercaseAtSentenceBoundary())

用于更正拼写错误

如果您还想更正文本中的任何拼写错误,您可能还想考虑使用 UITextChecker class(您确实提到了自动更正,所以我想我会添加这在)。

NSHipster has a nice tutorial on how to use it。这是他们教程中的代码示例。

import UIKit

let str = "hipstar"
let textChecker = UITextChecker()
let misspelledRange =
    textChecker.rangeOfMisspelledWord(in: str,
                                      range: NSRange(0..<str.utf16.count),
                                      startingAt: 0,
                                      wrap: false,
                                      language: "en_US")

if misspelledRange.location != NSNotFound,
    let firstGuess = textChecker.guesses(forWordRange: misspelledRange,
                                         in: str,
                                         language: "en_US")?.first
{
    print("First guess: \(firstGuess)") // First guess: hipster
} else {
    print("Not found")
}

正在获取要检查的文本:

如果您使用 UITextField, implement the UITextFieldDelegate 在文本字段完成编辑时通过 textFieldShouldEndEditing(_:) 方法检查字符串的拼写。

如果您使用 UITextView, you can use the similar UITextViewDelegate 方法来确定何时检查和替换字符串中的各个单词。