Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 如何获取字符串中每个单词的第一个字符?_Ios_Swift - Fatal编程技术网

Ios 如何获取字符串中每个单词的第一个字符?

Ios 如何获取字符串中每个单词的第一个字符?,ios,swift,Ios,Swift,我想要这个: var String1 = "Stack Over Flow" var desiredOutPut = "SOF" // the first Character of each word in a single String (after space) 我知道如何从字符串中获取第一个字符,但不知道如何处理此问题。您可以使用此方法获取字符串数组。使用“作为分隔符 由于您知道如何获取字符串的第一个字符,现在只需对数组中的每个字符串执行此操作。您可以尝试以下代码: 如果组件按字符串

我想要这个:

var String1 = "Stack Over Flow"
var desiredOutPut = "SOF" // the first Character of each word in a single String (after space)
我知道如何从字符串中获取第一个字符,但不知道如何处理此问题。

您可以使用此方法获取字符串数组。使用
作为分隔符

由于您知道如何获取字符串的第一个字符,现在只需对数组中的每个字符串执行此操作。

您可以尝试以下代码:



如果
组件按字符串分隔有问题,您可以尝试按字符空间分隔,并在数组中继续删除所有空字符串

希望这有帮助

或使用
.reduce()




顺便说一句,我认为变量名的约定是驼峰大小写,第一个字符是小写字母,例如“string1”而不是“string1”

为了使其更优雅,我将使用以下代码对swift 3.0 String类进行扩展

extension String
{
    public func getAcronyms(separator: String = "") -> String
    {
        let acronyms = self.components(separatedBy: " ").map({ String($0.characters.first!) }).joined(separator: separator);
        return acronyms;
    }
}
后记你可以这样使用它:

  let acronyms = "Hello world".getAcronyms();
  //will print: Hw

  let acronymsWithSeparator = "Hello world".getAcronyms(separator: ".");
  //will print: H.w

  let upperAcronymsWithSeparator = "Hello world".getAcronyms(separator: ".").uppercased();
  //will print: H.W
extension String {
  func acronym() -> String {
    return self.components(separatedBy: .whitespaces).filter { !$0.isEmpty }.reduce("") { $0.0 + String($0.1.characters.first!) }
  }
}

这是swift3的变化

      let stringInput = "Stack Overflow"
      let stringInputArr = stringInput.components(separatedBy: " ")
      var stringNeed = ""

      for string in stringInputArr {
           stringNeed = stringNeed + String(string.characters.first!)
      }

      print(stringNeed)

SWIFT 3

为了避免单词之间有多个空格(即
John Smith
)时发生崩溃,可以使用以下方法:

  let acronyms = "Hello world".getAcronyms();
  //will print: Hw

  let acronymsWithSeparator = "Hello world".getAcronyms(separator: ".");
  //will print: H.w

  let upperAcronymsWithSeparator = "Hello world".getAcronyms(separator: ".").uppercased();
  //will print: H.W
extension String {
  func acronym() -> String {
    return self.components(separatedBy: .whitespaces).filter { !$0.isEmpty }.reduce("") { $0.0 + String($0.1.characters.first!) }
  }
}
如果您还想包含换行符,只需将
.whitespaces
替换为
.whitespaces和newlines

Note that if you're experiencing error: 
无法使用类型为“(字符串,()->”)的参数列表调用“reduce”

labelForContext.text = self.components(separatedBy: " ").reduce("") { first, next in 
     (first) + (next.first.map { String($0) } ?? "")
}

为了完整性起见,这是一个具有非常强大的
枚举子字符串的解决方案(in:options:\uu:

let string = "Stack Over Flow"

var result = ""
string.enumerateSubstrings(in: string.startIndex..<string.endIndex, options: .byWords) { (substring, _, _, _) in
    if let substring = substring { result += substring.prefix(1) }
}
print(result)
let string=“堆栈溢出”
var result=“”

EnumerateSubstring(in:string.startIndex..请参阅将字符串拆分为单词数组。嘿,谢谢:)@vienvu工作正常,但你能告诉我我们在这里做什么吗?我的意思是,代码不知道它们是如何执行任务的task@Montanabucks在这种情况下,我的想法是:我们可以用空格字符将一个字符串分隔成一个数组。您的gold是获取每个字符串的第一个字符,因此我们在这个数组中运行一个循环。我们可以获取它的第一个字符。因为它是字符,所以我们需要转换为字符串。我们需要字符串来保存结果。因此,每个循环都要将其转换。当结束循环时,我们将得到您需要的结果。请注意,如果
组件(分隔符:)
方法返回空字符串,则此操作将崩溃。即,原始字符串以空格
let stringInput=“First Last”
@Montanabucks总是乐于帮助!Swift 3更新:
var desiredOutPut=String1.components(以:“”分隔)。reduce(“”{$0.0+String($0.1.characters.First!)}
感谢您的帮助,是的,我正在跟踪您:)学习后,我会记住这一点没问题。检查first是否为非nil很重要,因为如果String1以空格结尾,它可能为nil,在这种情况下,数组中的最后一项可能是空字符串。以下是Swift编程书的摘录:“无论何时定义新的类或结构,都会有效地定义一个全新的Swift类型。请为类型指定大写名称(如此处的SomeClass和SomeStructure),以匹配标准Swift类型(如String、Int和Bool)的大小写。相反,请始终为属性和方法指定小写名称。”(如frameRate和incrementCount)将其与类型名称区分。“摘自:Apple Inc.“Swift编程语言(Swift 2.1预发行版)。”iBooks。请注意,如果字符串以空格结尾->“Hello world”,则代码不起作用"拆分字符串并打印该拆分字符串的第一个字母此答案只是1.5年前OP的任何其他答案的重复。仅使用
。byWords
选项,子字符串永远不会为零。枚举的子字符串。如果子字符串NotRequired包含在opts中,则每次执行闭包时,此参数都为零。
结果+=substring!.prefix(1)
如果你想变得特别偏执
result+=substring?。prefix(1)?“”
labelForContext.text = self.components(separatedBy: " ").reduce("") { first, next in 
     (first) + (next.first.map { String($0) } ?? "")
}
let string = "Stack Over Flow"

var result = ""
string.enumerateSubstrings(in: string.startIndex..<string.endIndex, options: .byWords) { (substring, _, _, _) in
    if let substring = substring { result += substring.prefix(1) }
}
print(result)
let inputString = "ABC PQR XYZ"
var stringNeed = ""

class something
{
        let splits = inputString.components(separatedBy: " ")
        for string in splits
        {
            stringNeed = stringNeed + String(string.first!)      
        }
        print(stringNeed)
}