我正在编写一个程序,以删除字符串中存在的字母。但是预期的结果不会到来。我尝试过的程序如下:-
package main
import (
"fmt"
"strings"
)
func main() {
strValue := "This is a string"
stringRemove := []string{"a", "an"}
var removalString string
for _, wordToRemove := range stringRemove {
removalString = strings.Replace(strValue, wordToRemove, "", -1)
}
fmt.Println(removalString)
result := strings.Replace(strValue, " ", "", -1)
result1 := strings.ToLower(result)
fmt.Println(result1)
}
输出:-
This is a string
thisisastring
如果我在for循环中使用行fmt.Println(removalString)
,则它将打印结果:-
输出:-
This is string
This is a string
This is a string
thisisastring
预期输出:-
thisisstring
答案 0 :(得分:2)
您始终对原始字符串strValue
进行替换操作,因此在循环之后,仅最后一个可移动单词将被删除(示例中甚至没有包含)。您应该存储strings.Replace()
的结果(执行此操作),并在下一次迭代中使用它:
removalString := strValue
for _, wordToRemove := range stringRemove {
removalString = strings.Replace(removalString, wordToRemove, "", -1)
}
并在最后一次替换中使用它:
result := strings.Replace(removalString, " ", "", -1)
result1 := strings.ToLower(result)
然后将输出(在Go Playground上尝试):
This is string
thisisstring
还请注意,要删除空格,可以将其添加到可移动单词的列表中,并且不必总是创建新变量,可以重复使用现有变量。
这还将执行相同的转换:
s := "This is a string"
words := []string{"a", "an", " "}
for _, word := range words {
s = strings.Replace(s, word, "", -1)
}
s = strings.ToLower(s)
fmt.Println(s)
在Go Playground上尝试。
答案 1 :(得分:0)
这是您要寻找的:
package main
import (
"fmt"
"strings"
)
func main() {
strValue := "This is a string"
stringRemove := []string{"a", "an"}
removalString := strValue
for _, wordToRemove := range stringRemove {
removalString = strings.Replace(removalString, wordToRemove, "", -1)
}
fmt.Println(removalString)
result := strings.Replace(strValue, " ", "", -1)
result1 := strings.ToLower(result)
fmt.Println(result1)
}
答案 2 :(得分:0)
removalString
将在每个循环中设置新值。因此fmt.Println(removalString)
将显示上一循环的结果。
var removalString string
for _, wordToRemove := range stringRemove {
removalString = strings.Replace(strValue, wordToRemove, "", -1)
}
fmt.Println(removalString)
您可能会这样
strValue := "This is a string"
stringRemove := []string{"a", "an"}
for _, wordToRemove := range stringRemove {
strValue = strings.Replace(strValue, wordToRemove, "", -1)
}
fmt.Println(strValue)