Home >Backend Development >Golang >Return values ​​from 'map' and print them

Return values ​​from 'map' and print them

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBforward
2024-02-05 22:09:031247browse

Return values ​​from map and print them

Question content

I just want to print the output of the map function...

Input: "Hello World" Expected output: map['h': 1, 'e': 1, 'l': 3, 'o': 2, 'r': 1, 'w': 1, 'd':1,'':1] My code:

65 BC 550325d8 65 BC 550325e6

expect: Map['h': 1, 'e': 1, 'l': 3, 'o': 2, 'r': 1, 'w': 1, 'd': 1, ' ': 1]

fmt.println(characters) gave me the following Map[32:1 100:1 101:1 104:1 108:3 111:2 114:1 119:1]

fmt.printf("%c", char) gives me the following Map[ :☺ d:☺ e:☺ h:☺ l:♥ o:☻ r:☺ w:☺]

fmt.printf("%c", map[rune]int) Explosion ".\10_go_map_dict_q1.go:29:19: map[rune]int (type) is not an expression"


Correct answer


package main

import "fmt"

func main() {
    CharacterFrequency("hello world")
}

func CharacterFrequency(sentence string) map[string]int {
    characters := map[string]int{}
    for _, char := range sentence {
        characters[string(char)]++
    }
    fmt.Printf("%v", characters)
    // Output: map[ :1 d:1 e:1 h:1 l:3 o:2 r:1 w:1]
    return characters
}

The above is the detailed content of Return values ​​from 'map' and print them. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete