Naro Naro - 1 year ago 54
Swift Question

Trying to count Characters from user input but it is also counting [""] not just the users input word.

I am trying to count and display the character count from a users input word. I kind of figured out how to change the word from a string to a character but it shows the [""] in the count along with the letters. I need it to just count and display the letters. Example: user inputs Test,
Letter : Count
e : 1,
s : 1,
t : 2
(Can't get it to show like it should in the program)
Number of keys in charcount dictionary: 3

import Foundation
var myWord: [String] = [] //Array for word given by user
//var count = 0 //create a variable to hold the count for any matches

//get input from user - must use Objective C code since Swift 1+ doesn't have an input function (code used from Dawn Wick StudentTests code)
func input() -> String {
let keyboard = NSFileHandle.fileHandleWithStandardInput()
let inputData = keyboard.availableData
let strData = NSString(data: inputData, encoding: NSUTF8StringEncoding)!
return strData.stringByTrimmingCharactersInSet(NSCharacterSet.newlineCharacterSet())

print("Enter a word: ", terminator: "")

var userWord = input() // get users word
myWord.append(userWord) //Append myWord array with user input

//Summarize character counts
var charCount: [Character : Int] = [:]

//Summarize occurences of each character
for char in myWord.description.characters{
//if char in Dictionary, increment count, otherwise add it
if let count = charCount[char] {
charCount[char] = count + 1 //increment count
}else {
charCount[char] = 1 //add char to dictionary

print("THE WORD \(myWord) CONTAINS:", terminator: " ");
print("\nLETTERS\t\t COUNT\n", terminator: " ");
for (char, count) in charCount {
print("\n \(char) \t \(count)", terminator: " ");
print("\nNumber OF KEYS IN CHARCOUNTS DICTIONARY: \(charCount.count)", terminator: " ");

I would be very grateful for any help.
Thank you.

Answer Source

Because you're using myWord.description.characters, you're getting the [, ] and ".

You should be using:

myWord.forEach {
    $0.characters.forEach {
        charCount[$0] = (charCount[$0] ?? 0) + 1

Since you're counting all the Characters and put them in dictionary, you could simplify it a bit:

myWord.flatMap { $0.characters }.forEach {
    charCount[$0] = (charCount[$0] ?? 0) + 1
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download