douwen5066 2018-11-26 11:12
浏览 162

使用Go从字符串中删除所有文章和其他字符串?

Is there any method in Go or having regular expression that it will remove only the articles used in the string?

I have tried below code that will do it but it will also remove other words from the string I'm showing the code below:

 removalString := "This is a string"
 stringToRemove := []string{"a", "an", "the", "is"}
 for _, wordToRemove := range stringToRemove {
     removalString = strings.Replace(removalString, wordToRemove, "", -1)
 }
 space := regexp.MustCompile(`\s+`)
 trimedExtraSpaces := space.ReplaceAllString(removalString, " ")
 spacesCovertedtoDashes := strings.Replace(trimedExtraSpaces, " ", "-", -1)
 slug := strings.ToLower(spacesCovertedtoDashes)
 fmt.Println(slug)

Edited

Play link

In this It will remove the is which is used in the this.

The Expected output is this-string

  • 写回答

2条回答 默认 最新

  • doudi1750 2018-11-26 11:28
    关注

    You can use strings.Split and strings.Join plus a loop for filtering and then building it together again:

    removalString := "This is a string"
    stringToRemove := []string{"a", "an", "the", "is"}
    filteredStrings := make([]string, 0)
    for _, w := range strings.Split(removalString, " ") {
        shouldAppend := true
        lowered := strings.ToLower(w)
        for _, w2 := range stringToRemove {
            if lowered == w2 {
                shouldAppend = false
                break
            }
        }
        if shouldAppend {
            filteredStrings = append(filteredStrings, lowered)
        }
    }
    resultString := strings.Join(filteredStrings, "-")
    fmt.Printf(resultString)
    

    Outpus:

    this-string
    Program exited.
    

    Here you have the live example

    评论

报告相同问题?

悬赏问题

  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作