【问题标题】:How to capitalize first word in every sentence with Swift如何使用 Swift 将每个句子中的第一个单词大写
【发布时间】:2015-05-30 17:42:03
【问题描述】:

考虑到用户的语言环境,如何将段落中每个句子的第一个单词大写?我想要实现的是无论句子里面的大小写,每个单词的第一个字母都是大写的,其余的都是小写的。我只能做一个句子,首先将所有内容转换为小写,然后获取第一个字母并变为大写,最后将它们加在一起。我的问题与How to capitalize each word in a string using Swift iOS 不同,因为我不想将每个单词都大写。我只想将每个句子的第一个单词大写。 capitalizedString转

"this is first sentence. this is second sentence."

到

"This Is First Sentence. This Is Second Sentence."

我想要的是

"This is first sentence. This is second sentence."

我的问题也与Capitalise first letter of every sentence 不同,因为@rintaro 的代码不适用于我下面的示例。它使原始文本中的大写字母保持不变。使用@rintaro 的代码;

之前

"someSentenceWith UTF text İŞğĞ. anotherSentenceğüÜğ"

之后

"SomeSentenceWith UTF text İŞğĞ. AnotherSentenceğüÜğ."

我想要达到的,

"Somesentencewith utf text işğğ. Anothersentenceğüüğ." 

我下面的代码只能进行部分转换。

var description = "someSentenceWith UTF text İŞğĞ. anotherSentenceğüÜğ"
description = description.lowercaseStringWithLocale(NSLocale.currentLocale())
let first = description.startIndex
let rest = advance(first,1)..<description.endIndex
let capitalised = description[first...first].uppercaseStringWithLocale(NSLocale.currentLocale()) + description[rest]

如果您能仔细阅读我的问题,我将不胜感激,因为这是我第三次编辑问题。由于我不是母语人士,如果不能清楚地问出来,我真的很抱歉。所以即使@rintaro 回答了类似的问题,他的回答并没有解决我的问题。 @martin-r 提出了一个 Objective-C 的答案,它再次不能解决我遇到的问题。还有另一个用户 eric something 也提出了另一个答案,但后来被删除了。我只是不明白为什么有几个人提出了不同的答案而没有回答我的问题。

【问题讨论】:

  • 我重新打开了这个问题。我承认我忽略了 "and the rest will be lowercase" 部分(这在最初的示例中并不明显)并道歉。
  • 在我看来,对 rintaro 代码的微小修改应该会得到您想要的结果:只需将 result += String(first).uppercaseString + substring 替换为 result += String(first).uppercaseString + substring.lowercaseString。
  • 先生,我对您的行为感到非常失望。您多次给出/批准了错误的答案,将问题锁定为重复。当然,它们现在已被删除,因此我无法证明任何这些事情。无论如何,下次我该怎么办,以免下次我把铲子塞进喉咙里?

标签: swift nsstring


【解决方案1】:

我根据@Katy 的代码在 Swift 3 中编写了这个扩展

extension String {

func toUppercaseAtSentenceBoundary() -> String {

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

    return result as String 
  }
}

使用方法:

let string = "This is First sentence. This is second Sentence.".toUppercaseAtSentenceBoundary() 
print(string) /* Output: "This is first sentence. This is second sentence." */

【讨论】:

    【解决方案2】:

    为 Swift 3 更新 @rintaro 的代码:

    let str = "someSentenceWith UTF text İŞğĞ. anotherSentenceğüÜğ"
    
    var result = ""
    str.uppercased().enumerateSubstrings(in: str.startIndex..<str.endIndex, options: .bySentences) { (sub, _, _, _)  in
        result += String(sub!.characters.prefix(1))
        result += String(sub!.characters.dropFirst(1)).lowercased()
    }
    
    print(result)
    

    【讨论】:

      【解决方案3】:

      试试:

      let str = "someSentenceWith UTF text İŞğĞ. anotherSentenceğüÜğ"
      
      var result = ""
      str.uppercaseString.enumerateSubstringsInRange(indices(str), options: .BySentences) { (sub, _, _, _)  in
          result += sub[sub.startIndex ... sub.startIndex]
          result += sub[sub.startIndex.successor() ..< sub.endIndex].lowercaseString
      }
      
      println(result) // -> "Somesentencewith utf text i̇şğğ. Anothersentenceğüüğ"
      

      添加:Swift2

      let str = "someSentenceWith UTF text İŞğĞ. anotherSentenceğüÜğ"
      
      var result = ""
      str.uppercaseString.enumerateSubstringsInRange(str.characters.indices, options: .BySentences) { (sub, _, _, _)  in
          result += String(sub!.characters.prefix(1))
          result += String(sub!.characters.dropFirst(1)).lowercaseString
      }
      
      print(result)
      

      【讨论】:

      • rintaro,你好心更新你对 Swift 3 的答案吗?
      【解决方案4】:

      您可以使用正则表达式来实现这一点。我将此函数添加为字符串扩展,因此将来调用它会很简单:

      extension String {
      
          func toUppercaseAtSentenceBoundary() -> String {
              var string = self.lowercaseString
      
              var capacity = string.utf16Count
              var mutable = NSMutableString(capacity: capacity)
              mutable.appendString(string)
      
              var error: NSError?
      
              if let regex = NSRegularExpression(
                  pattern: "(?:^|\\b\\.[ ]*)(\\p{Ll})",
                  options: NSRegularExpressionOptions.AnchorsMatchLines,
                  error: &error
                  ) {
      
                  if let results = regex.matchesInString(
                      string,
                      options: NSMatchingOptions.allZeros,
                      range: NSMakeRange(0, capacity)
                      ) as? [NSTextCheckingResult] {
      
                          for result in results {
                              let numRanges = result.numberOfRanges
                              if numRanges >= 1 {
                                  for i in 1..<numRanges {
                                      let range = result.rangeAtIndex(i)
                                      let substring = mutable.substringWithRange(range)
                                      mutable.replaceCharactersInRange(range, withString: substring.uppercaseString)
                                  }
                              }
                          }
                  }
              }
      
              return mutable
          }
      }
      
      var string = "someSentenceWith UTF text İŞğĞ. anotherSentenceğüÜğ.".toUppercaseAtSentenceBoundary()
      

      【讨论】:

      • 感谢您的帮助。由于这里一些人的行为,我感到非常压力。
      • 谢谢,但必须是 "(?:^|\\b(\\.|\\!|\\?)[ ]*)(\\p{Ll})"匹配任何标点符号,而不是句号。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-20
      • 1970-01-01
      • 1970-01-01
      • 2011-01-26
      • 1970-01-01
      • 1970-01-01
      • 2014-07-11
      相关资源
      最近更新 更多