访问量: 10 次浏览
当我们从一个字符串中移除空格时,意味着移除空白、制表符和其他空白字符,包括换行符。
这对于解析用户输入或处理特定格式的数据很有帮助,在其他情况下,我们希望在进一步处理字符串之前对其进行清理或标准化。
有各种方法来消除字符串中的空白。几个例子包括:使用 TrimSpace 函数,消除字符串开头和结尾的空白字符;使用 Replace 函数,用一个完全为空的字符串替换字符串中的任何空白字符;并使用 regexp 包,可以消除所有空白字符。
在这篇文章中,我们将看到如何使用 Golang 的例子来消除字符串中的空白处。
strings.Replace() 函数在这个方法中,strings.Replace() 函数被指示用第三个参数(-1)来替换所有实例。
之后,一个没有空白的字符串被打印出来。让我们通过实例:和算法来更好地理解这个概念。
strings.Replace()
Golang中的字符串包提供了一个内置的 Replace 函数,可以用来将一个提供的字符串中的某个子串换成另一个子串。
Replace 函数需要三个参数:第一个字符串、被替换的子串和替换的子串。它给出了一个新的字符串,其中替换的子串被替换为原始子串的每个实例。
main,并在程序中声明 fmt(格式包)和 strings 包,其中 main 产生可执行的例子,fmt 帮助格式化输入和输出。mystr 的初始值。Replace 函数。该函数被指示用第三个参数(-1)来替换所有实例。fmt.Println() 函数将更新后的字符串打印到控制台,其中 ln 表示新行。在这个例子中,我们使用 Replace 函数将空格字符(" ")的每个实例替换为空字符串。
package main
import (
"fmt"
"strings"
)
func main() {
mystr := "Hi i am an engineer i work as a frontend developer" //create strings
fmt.Println("The string before removal of whitespaces is:", mystr)
mystr = strings.Replace(mystr, " ", "", -1) //using this built-in function remove whitespaces
fmt.Println("The string after removing whitespaces is:")
fmt.Println(mystr) //remove string without whitespaces
}
The string before removal of whitespaces is: Hi i am an engineer i work as a frontend developer
The string after removing whitespaces is:
Hiiamanengineeriworkasafrontenddeveloper
regexp.Compile 方法这个例子中的字符串已经用正则表达式去掉了所有的空白。
为了创建一个匹配一个或多个空白字符(\s+)的正则表达式模式,我们利用了 regexp 包。
然后使用 ReplaceAllString 函数将模式匹配的每个实例替换为空字符串。
之后,一个没有空白的字符串被打印出来。让我们通过示例和算法来了解另一种从字符串中删除空白的方法。
regexp.Compile()
regexp.Compile()
Go 中的正则表达式可以使用 regexp 包中的 Compile 函数编译成更有效的形式进行匹配。
正则表达式模式作为单个参数传递给 Compile 函数,该函数返回一个 \*Regexp 结构。
main,并在程序中声明 fmt(格式包)和 regexp 包,其中 main 产生可执行的示例,fmt 帮助格式化输入和输出。main 函数中,将你想删除空白的字符串设置为变量 mystr 的初始值。regexp 创建一个正则表达式模式,匹配一个或多个空白字符。\s+ReplaceAllString 方法,用 reg 替换所有模式匹配的空字符串。ReplaceAllString(str, "") 这样的字符串去掉空白处。fmt.Println() 函数在控制台打印更新的字符串,其中 ln 表示新行。在这个例子中,我们将使用 Golang 的 regexp.Compile() 函数来删除一个字符串的所有空格
package main
import (
"fmt"
"regexp"
)
func main() {
mystr := "Hi i am a frontend developer" //create string
fmt.Println("The string before removal of whitespaces is:", mystr)
reg, _ := regexp.Compile("\\s+") //compile
mystr = reg.ReplaceAllString(mystr, "") //remove whitespaces
fmt.Println("The string after removal of whitespaces is:")
fmt.Println(mystr) //print string without whitespaces
}
The string before removal of whitespaces is: Hi i am a frontend developer
The string after removal of whitespaces is:
Hiiamafrontenddeveloper
我们用两个例子执行了删除字符串中所有空白的程序。
在第一个例子中,我们使用了 strings.Replace() 函数,这是一个内置函数;在第二个例子中,我们使用了 regexp.Compile() 函数。