簡體   English   中英

Swift 3.0 遍歷 String.Index 范圍

[英]Swift 3.0 iterate over String.Index range

Swift 2.2 可以實現以下功能:

let m = "alpha"
for i in m.startIndex..<m.endIndex {
    print(m[i])
}
a
l
p
h
a

使用 3.0,我們會收到以下錯誤:

類型“范圍”(又名“范圍”)不符合協議“序列”

我正在嘗試對 swift 中的字符串執行一個非常簡單的操作——簡單地遍歷字符串的前半部分(或者更一般的問題:遍歷字符串的范圍)。

我可以執行以下操作:

let s = "string"
var midIndex = s.index(s.startIndex, offsetBy: s.characters.count/2)
let r = Range(s.startIndex..<midIndex)
print(s[r])

但在這里我並沒有真正遍歷字符串。 所以問題是:如何遍歷給定字符串的范圍。 喜歡:

for i in Range(s.startIndex..<s.midIndex) {
    print(s[i])
}

您可以使用characters屬性的indices屬性遍歷字符串,如下所示:

let letters = "string"
let middle = letters.index(letters.startIndex, offsetBy: letters.characters.count / 2)

for index in letters.characters.indices {

    // to traverse to half the length of string 
    if index == middle { break }  // s, t, r

    print(letters[index])  // s, t, r, i, n, g
}

字符串和字符 - 計數字符部分中的文檔

擴展的字形集群可以由一個或多個Unicode標量組成。 這意味着不同的字符和相同字符的不同表示可能需要不同的內存量來存儲。 因此,Swift中的字符不會在字符串表示中占用相同數量的內存。 因此,如果不迭代字符串以確定其擴展的字形集群邊界, 則無法計算字符串中的字符數

重點是我自己的。

這不起作用:

let secondChar = letters[1] 
// error: subscript is unavailable, cannot subscript String with an Int

另一種選擇是使用enumerated()例如:

let string = "Hello World"    
for (index, char) in string.characters.enumerated() {
    print(char)
}

或者對於Swift 4只是使用

let string = "Hello World"    
for (index, char) in string.enumerated() {
    print(char)
}

使用以下內容:

for i in s.characters.indices[s.startIndex..<s.endIndex] {
  print(s[i])
}

自從Swift 2.2遷移到Swift 2.3或Swift 3

在Swift 4中迭代字符串中的字符更清晰:

let myString = "Hello World"    
for char in myString {
    print(char)
}

如果要遍歷String的字符,那么您可以簡單地使用符合CollectionTypeStringCharacterView ,而不是顯式訪問String的索引,從而允許您訪問整齊的子序列方法,例如prefix(_:)等等。

/* traverse the characters of your string instance,
   up to middle character of the string, where "middle"
   will be rounded down for strings of an odd amount of
   characters (e.g. 5 characters -> travers through 2)  */
let m = "alpha"
for ch in m.characters.prefix(m.characters.count/2) {
    print(ch, ch.dynamicType)
} /* a Character
     l Character */

/* round odd division up instead */
for ch in m.characters.prefix((m.characters.count+1)/2) {
    print(ch, ch.dynamicType)
} /* a Character
     l Character 
     p Character */

如果您想將循環中的字符視為字符串,只需使用上面的String(ch)


關於下面的評論:如果您想訪問一系列的CharacterView ,您可以輕松實現自己的CollectionType擴展(在Generator.ElementCharacter時指定),同時使用prefix(_:)suffix(_:)產生一個子集合,例如半開( from..<to )范圍

/* for values to >= count, prefixed CharacterView will be suffixed until its end */
extension CollectionType where Generator.Element == Character {
    func inHalfOpenRange(from: Int, to: Int) -> Self {
        guard case let to = min(to, underestimateCount()) where from <= to else {
            return self.prefix(0) as! Self
        }
        return self.prefix(to).suffix(to-from) as! Self
    }
}

/* example */
let m = "0123456789"    
for ch in m.characters.inHalfOpenRange(4, to: 8) {
    print(ch)         /*  \                                   */
} /* 4                     a (sub-collection) CharacterView
     5
     6
     7 */

最好的方法是: -

 let name = "nick" // The String which we want to print.

  for i in 0..<name.count 
{
   // Operation name[i] is not allowed in Swift, an alternative is
   let index = name.index[name.startIndex, offsetBy: i]
   print(name[index])
}

有關詳細信息,請訪問此處

斯威夫特4:

let mi: String = "hello how are you?"
for i in mi {
   print(i)
}

為了具體演示如何遍歷Swift 4中字符串中的范圍,我們可以使用for循環中的where過濾器將其執行過濾到指定范圍:

func iterateStringByRange(_ sentence: String, from: Int, to: Int) {

    let startIndex = sentence.index(sentence.startIndex, offsetBy: from)
    let endIndex = sentence.index(sentence.startIndex, offsetBy: to)

    for position in sentence.indices where (position >= startIndex && position < endIndex) {
        let char = sentence[position]
        print(char)
    }

}

iterateStringByRange("string", from: 1, to: 3)將打印tri

Swift 4.2

只是:

let m = "alpha"
for i in m.indices {
   print(m[i])
}

遍歷字符串中字符的索引時,很少只需要索引。 您可能還需要給定索引處的字符。 正如 Paulo 所指定的(針對 Swift 4+ 進行了更新), string.indices將為您提供字符的索引。 zip可用於組合索引和字符:

let string = "string"

// Define the range to conform to your needs
let range = string.startIndex..<string.index(string.startIndex, offsetBy: string.count / 2)
let substring = string[range]
// If the range is in the type "first x characters", like until the middle, you can use:
//  let substring = string.prefix(string.count / 2)

for (index, char) in zip(substring.indices, substring) {
    // index is the index in the substring
    print(char)
}

請注意,使用enumerated()會產生一對索引和字符,但索引不是字符在字符串中的索引。 它是枚舉中的索引,可以不同。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM