我想删除String值中的空格,例如:“ I skd a efju N”到“ IdskdaefjuN”,但它不起作用...
我尝试使用:
stringValue = strings.Replace(stringValue, " ", "", -1)
package main
import (
"fmt"
"strings"
)
func main() {
//var String
var stringValue string
var originalValue string
fmt.Printf("please, type some text:")
//user input
fmt.Scan(&stringValue)
originalValue = stringValue
//remove spaces
stringValue = strings.Replace(stringValue, " ", "", -1)
//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)
}
}
答案 0 :(得分:2)
如何在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
答案 1 :(得分:1)
当我尝试运行您的代码时,无法使用fmt.Scan()
从stdin正确读取。如果将其替换为从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)
}
}
答案 2 :(得分:1)
这对我有用
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)
}
只需将空格替换为空字符串,请参阅此处的官方 documentation