Swift程式:查詢字串中字元的頻率
在Swift中,字串中所有字元的頻率是指字元在一個給定字串中重複出現的次數。例如,“Swift tutorial”,其中“t”在給定字串中重複出現3次,“i”重複出現2次。因此,在本文中,我們將找到字串中所有字元的頻率。
演算法
步驟1 − 建立一個變數來儲存字串。
步驟2 − 建立一個字典來儲存字元及其計數。
步驟3 − 執行for迴圈來迭代輸入字串中的每個字元。
步驟4 − 現在我們檢查當前字元是否出現超過1次,如果是,則每次出現時計數增加1。
步驟5 − 如果不是,則將當前字元儲存到字典中,計數為1。
步驟6 − 再次執行for-in迴圈來顯示字元及其在字串中的總出現次數。
示例
在下面的Swift程式中,我們將查詢字串中字元的頻率。首先,我們將建立一個字串和一個空字典來儲存字元及其頻率計數。然後,我們將執行一個for-in迴圈來遍歷輸入字串的每個字元。如果一個字元出現多次,我們將每次出現時將其計數增加一。如果不是,則將其計數設定為一。最後,我們將結果顯示在輸出螢幕上。
import Foundation import Glibc let EnteredString = "This is Swift Tutorial" print("Input String is: ", EnteredString) var charCount = [Character:Int]() for C in EnteredString { if let size = charCount[C]{ charCount[C] = size+1 } else { charCount[C] = 1 } } for (C, size) in charCount { print("Character:\(C) occurs \(size) times in the given string") }
輸出
Input String is: This is Swift Tutorial Character:S occurs 1 times in the given string Character:a occurs 1 times in the given string Character:l occurs 1 times in the given string Character:w occurs 1 times in the given string Character:i occurs 4 times in the given string Character:T occurs 2 times in the given string Character:o occurs 1 times in the given string Character:u occurs 1 times in the given string Character:t occurs 2 times in the given string Character:f occurs 1 times in the given string Character:r occurs 1 times in the given string Character:s occurs 2 times in the given string Character:h occurs 1 times in the given string Character: occurs 3 times in the given string
結論
這就是我們如何找到給定字串中所有字元的頻率或出現次數的方法。上述方法查詢所有字元的出現總數以及給定字串中使用的總空格數。因此,只需對程式碼進行少量更改,就可以僅查詢給定字串中使用的總空格數。
廣告