登录
首页 >  Golang >  Go问答

GO语言中如何实现字符串转为小写?

来源:stackoverflow

时间:2024-02-10 18:51:15 432浏览 收藏

今日不肯埋头,明日何以抬头!每日一句努力自己的话哈哈~哈喽,今天我将给大家带来一篇《GO语言中如何实现字符串转为小写?》,主要内容是讲解等等,感兴趣的朋友可以收藏或者有更好的建议在评论提出,我都会认真看的!大家一起进步,一起学习!

问题内容

我是 go 语言的新手,正在做一项作业,我应该编写一个返回文本词频的代码。但是我知道“hello”、“hello”和“hello”这三个词都算作“hello”,所以我需要将所有字符串转换为小写。

我知道我应该使用 strings.tolower(),但是我不知道应该将其包含在类中。有人可以帮我吗?

package main

import (
    "fmt"
    "io/ioutil"
    "log"
    "strings"
    "time"
)

const DataFile = "loremipsum.txt"

// Return the word frequencies of the text argument.
func WordCount(text string) map[string]int {
    fregs := make(map[string]int)
    words := strings.Fields(text)
    for _, word := range words {
        fregs[word] += 1
    }
    return fregs
}

// Benchmark how long it takes to count word frequencies in text numRuns times.
//
// Return the total time elapsed.
func benchmark(text string, numRuns int) int64 {
    start := time.Now()
    for i := 0; i < numRuns; i++ {
        WordCount(text)
    }
    runtimeMillis := time.Since(start).Nanoseconds() / 1e6

    return runtimeMillis
}

// Print the results of a benchmark
func printResults(runtimeMillis int64, numRuns int) {
    fmt.Printf("amount of runs: %d\n", numRuns)
    fmt.Printf("total time: %d ms\n", runtimeMillis)
    average := float64(runtimeMillis) / float64(numRuns)
    fmt.Printf("average time/run: %.2f ms\n", average)
}

func main() {
    // read in DataFile as a string called data
    data, err:= ioutil.ReadFile("loremipsum.txt")
      if err != nil {
        log.Fatal(err)
        }

        // Convert []byte to string and print to screen

    text := string(data)
    fmt.Println(text)
    

    fmt.Printf("%#v",WordCount(string(data)))

    numRuns := 100
    runtimeMillis := benchmark(string(data), numRuns)
    printResults(runtimeMillis, numRuns)
}

正确答案


当您将单词用作地图键时,应将其转换为小写

for _, word := range words {
        fregs[strings.ToLower(word)] += 1
    }

以上就是《GO语言中如何实现字符串转为小写?》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>