2016-04-26 46 views
1

我想從字符串中創建一個字典,每個字的字符數。Swift如何從短語中得到一個帶字符數的字典

var textToShow:String = "Try not to become a man of success, but" //rather try to become a man of value. Albert Einstein" 

    print(charactersCount(textToShow)) 

func charactersCount(s: String) -> Dictionary<String, Int> { 
    var words = s.componentsSeparatedByString(" ") 
    var characterInWordDictionary = Dictionary<String, Int>() 

    for word in words { 
      characterInWordDictionary[word] = word.characters.count 
    } 
    return characterInWordDictionary 
} 

的問題是,這種梅索德,它返回

["Try": 3, "not": 3, "a": 1, "become": 6, "of": 2, "but": 3, "man": 3, "to": 2, "success,": 8] 

它並沒有那麼糟糕,但: - 第一,字典是不是在正確的順序 - 第二,我會就像字典裏的空間一樣。

我想回的是:

["Try": 3, " ": 1, "not": 3, " ": 1, "to": 2, " ": 1, "become": 6, " ": 1, "a": 1, " ": 1, "man": 3, " ": 1, "of": 2, " ": 1, "success,": 8, " ": 1, "but": 3] 

如果任何人都可以提供這方面的任何指導,這將是驚人的。

韓國社交協會,

+2

字典沒有順序。你需要一個元組數組 –

+1

字典是無序集合,所以你正在尋找的可能是一個元組''(String,Int)'而不是一個字典的數組。 – dfri

回答

1

首先創建一個空的tupleArray。接下來使用componentsSeparatedByString分解您的句子,並使用forEach遍歷所有元素(單詞)以追加該元素($ 0 =單詞)及其字符計數,後跟元組(「」,1)。然後,只需使用popLast刪除多餘的元組。像這樣嘗試:

let textToShow = "Try not to become a man of success, but" 

var tupleArray:[(String, Int)] = [] 

textToShow.componentsSeparatedByString(" ") 
      .forEach{tupleArray += [($0,$0.characters.count),(" ",1)]} 
tupleArray.popLast() 
print(tupleArray.description) // "[("Try", 3), (" ", 1), ("not", 3), (" ", 1), ("to", 2), (" ", 1), ("become", 6), (" ", 1), ("a", 1), (" ", 1), ("man", 3), (" ", 1), ("of", 2), (" ", 1), ("success,", 8), (" ", 1), ("but", 3)]\n" 
+0

問題在於,單詞之間的空格可能不總是長度爲1.另外,如果它以空格結束呢?或者如果它確實從空間開始。它並不涉及所有的情況。 –

+0

@MateHegedus這些案件的字符串沒有正確格式化 –

+0

你怎麼知道? –

1

我寫了一個小功能,爲你做這個:

var textToShow:String = "Try not to become a man of success, but" // rather try to become a man of value. Albert Einstein" 



func charactersCount(s: String) -> [(String, Int)] { 
    var result = [(String, Int)]() 

    var word = String(s[s.startIndex.advancedBy(0)]) 
    var size = 1 

    var space = s[s.startIndex.advancedBy(0)] == " " 

    for (var i:Int = 1; i < s.characters.count; i++) { 
     if (s[s.startIndex.advancedBy(i)] == " ") { 
      if (space) { 
       size++ 
       word.append(s[s.startIndex.advancedBy(i)]) 
      } else { 
       result.append((word, size)) 
       size = 1 
       space = true 
       word = " " 
      } 
     } else { 
      if (space) { 
       result.append((word, size)) 
       size = 1 
       space = false 
       word = String(s[s.startIndex.advancedBy(i)]) 
      } else { 
       size++ 
       word.append(s[s.startIndex.advancedBy(i)]) 
      } 
     } 
    } 
    result.append((word, size)) 

    return result 
} 

print(charactersCount(textToShow)) 

輸出是:

["Try": 3, " ": 1, "not": 3, " ": 1, "to": 2, " ": 1, "become": 6, " ": 1, "a": 1, " ": 1, "man": 3, " ": 1, "of": 2, " ": 1, "success,": 8, " ": 1, "but": 3] 
相關問題