dragonsun00000 2018-05-04 03:50
浏览 191
已采纳

golang string.ToLower无法正常工作

I have a simple input string which I need to read and count the repeated words.

But, while doing that I need to convert the string to lower case, but some how the func ToLower is not working.

I have attached the golang link, Please, help me understand what can be the issue.

https://play.golang.org/p/OnQW-pgQxqq

Also pasting the code.

func main() {
    input := `
one
two Two
three Three Three;
four four four, four
five? five. five, five Five`
    countwords(input)
}

type kv struct {
    key string
    val int
}

type kvlist []kv

// need to define custome interface to make this work:
func (kv kvlist) Less(i, j int) bool { return kv[i].val < kv[j].val }
func (kv kvlist) Swap(i, j int)      { kv[i], kv[j] = kv[j], kv[i] }
func (kv kvlist) Len() int           { return len(kv) }

//sort the words by value
func sortmap(wordmap map[string]int) []kv {
    list := make(kvlist, len(wordmap))
    i := 0
    for k, v := range wordmap {
        list[i] = kv{k, v}
        i++
    }
    // we need to make few more modification to change this but,
    // for now lets assume it works.
    sort.Sort(sort.Reverse(list))
    return list
}

func countwords(str string) []kv {
    count := make(map[string]int)
    reg, err := regexp.Compile("[^a-zA-Z0-9 ]+")
    if err != nil {
        log.Fatal(err)
    }
    lines := strings.Split(str, "
")
    for _, line := range lines {
        line := reg.ReplaceAllString(line, "")
        strings.ToLower(string(line))
        repeatwords := strings.Fields(line) // count the repeated words
        fmt.Println(repeatwords)
        for _, word := range repeatwords {
            if _, ok := count[word]; ok {
                count[word]++
            } else {
                count[word] = 1
            }
        }
    }
    //once counted now sort the map based on values(repeated words).
    ret := sortmap(count)
    fmt.Println(count)
    return ret
}
  • 写回答

1条回答 默认 最新

  • doumor942473 2018-05-04 03:58
    关注

    So, based on docs, strings.ToLower expects an string and RETURNS an string, so basically you have to assign the result of ToLower to a variable, something like the following will do the trick

    line = strings.ToLower(string(line))
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 ROS Turtlebot3 多机协同自主探索环境时遇到的多机任务分配问题,explore节点
  • ¥15 Matlab怎么求解含参的二重积分?
  • ¥15 苹果手机突然连不上wifi了?
  • ¥15 cgictest.cgi文件无法访问
  • ¥20 删除和修改功能无法调用
  • ¥15 kafka topic 所有分副本数修改
  • ¥15 小程序中fit格式等运动数据文件怎样实现可视化?(包含心率信息))
  • ¥15 如何利用mmdetection3d中的get_flops.py文件计算fcos3d方法的flops?
  • ¥40 串口调试助手打开串口后,keil5的代码就停止了
  • ¥15 电脑最近经常蓝屏,求大家看看哪的问题