4 回答
TA贡献1828条经验 获得超6个赞
Go 中如何删除空格
例如,
package main
import (
"fmt"
"unicode"
)
func removeSpace(s string) string {
rr := make([]rune, 0, len(s))
for _, r := range s {
if !unicode.IsSpace(r) {
rr = append(rr, r)
}
}
return string(rr)
}
func main() {
s := "I d skd a efju N"
fmt.Println(s)
s = removeSpace(s)
fmt.Println(s)
}
游乐场:https://play.golang.org/p/KoXZ24WXw7r
输出:
I d skd a efju N
IdskdaefjuN
TA贡献1846条经验 获得超7个赞
我用过这个
func cleanSpaces(stringToClean string) string {
result := strings.ReplaceAll(stringToClean, " ", "")
return result
}
或者
func cleanSpaces(stringToClean string) string {
fields := strings.Fields(stringToClean)
var result string
for i := 0; i < len(fields); i++ {
result += fields[i]
}
return result
}
TA贡献1942条经验 获得超3个赞
当我尝试运行您的代码时,它没有正确使用fmt.Scan(). 如果将其替换为从 stdin 读取的缓冲读取器,则它可以工作:
package main
import (
"bufio"
"fmt"
"os"
"strings"
)
func main() {
//var String
var stringValue string
var originalValue string
reader := bufio.NewReader(os.Stdin)
fmt.Printf("please, type some text:")
//user input
stringValue, _ = reader.ReadString('\n')
stringValue = strings.TrimSuffix(stringValue, "\n")
originalValue = stringValue
//remove spaces
stringValue = strings.ReplaceAll(stringValue, " ", "")
//set string to lower case
stringValue = strings.ToLower(stringValue)
//if contains substring "i", "a" and "n"
if strings.Contains(stringValue, "i") && strings.Contains(stringValue, "a") && strings.Contains(stringValue, "n") {
// if "i" is a prefix and "n" a suffix
firstChar := strings.HasPrefix(stringValue, "i")
lastChar := strings.HasSuffix(stringValue, "n")
switch {
//if is a prefix and suffix so Found
case firstChar && lastChar:
fmt.Printf("Found in %s", originalValue)
//if isnt a prefix and suffix so Not Found
default:
fmt.Printf("Not Found in %s", originalValue)
}
//if there's no "i", "a" and "n"
} else {
fmt.Printf("Not Found in %s", originalValue)
}
}
TA贡献1909条经验 获得超7个赞
这对我有用
package main
import (
"fmt"
"strings"
)
func main() {
x := " 1 ,2, 3,4,6 -3 0, 7, 8,70 -9 0"
x = strings.Replace(x, " ", "", -1)
fmt.Println(x)
}
只需将空格替换为空字符串,请参阅此处的官方文档
- 4 回答
- 0 关注
- 106 浏览
添加回答
举报