Home > front end >  How to convert a string to a dictionary of letters?
How to convert a string to a dictionary of letters?

Time:11-26

I need to convert letters into a dictionary of characters. Here's an example:

letter

l: 1
e: 2
t: 2
r: 1

I did some research and found this helpful answer, but that was using getline() and separating words by spaces. Since I am trying to split by character I don't think I can use getline() since '' isn't a valid split character. I could convert to a char* array but I wasn't sure where that would get me.

This is fairly easy in other languages so I thought it wouldn't be too bad in C . I was hoping there would be something like a my_map[key] or something. In Go I would write this as

// Word map of string: int values
var wordMap = make(map[string]int)

// For each letter, add to that key
for i := 0; i < len(word); i   {
    wordMap[string(word[i])]  
}

// In the end you have a map of each letter.

How could I apply this in C ?

CodePudding user response:

How could I apply this in C ?

It could look rather similar to your Go code.

// Word map of char: int values
// (strings would be overkill, since you know they are a single character)
auto wordMap = std::map<char,int>{};

// For each letter, add to that key
for ( char c : word )
    wordMap[c]  ;
}

CodePudding user response:

Here is the unicode version of Drew Dormann's answer:

#include <locale>
#include <codecvt>

std::string word = "some unicode: 仮φ";

std::map<char32_t, uint> wordMap;
std::wstring_convert<std::codecvt_utf8<char32_t>, char32_t> converter;

for (auto c : converter.from_bytes(word)) {
    wordMap[c]  ;
}

for (const auto [c, v] : wordMap) {
    std::cout << converter.to_bytes(c) << " : " << v << std::endl;
}
  • Related