golang removes leading and trailing spaces

王林
Release: 2023-05-10 10:58:06
Original
1503 people have browsed it

In golang, removing spaces before and after a string is a very common operation, such as getting a string entered by the user from a form, or reading data from a file. Here, we will introduce how to use the functions provided in the golang language to remove leading and trailing spaces from a string.

Method 1: Use the strings.TrimSpace() function

The golang standard library provides a function called strings.TrimSpace(), which can be used to remove leading and trailing spaces from a string. . The method of using this function is as follows:

package main

import (
    "fmt"
    "strings"
)

func main() {
    str := "  hello world  "
    trimmed := strings.TrimSpace(str)
    fmt.Println(trimmed)
}
Copy after login

The output result is:

hello world
Copy after login

Method 2: Using regular expressions

In addition to using functions in the standard library, we can also use Regular expression in golang to remove leading and trailing spaces from a string.

package main

import (
    "fmt"
    "regexp"
)

func main() {
    str := "  hello world  "
    trimmed := regexp.MustCompile(`^s+|s+$`).ReplaceAllString(str, "")
    fmt.Println(trimmed)
}
Copy after login

In the above example, we used the regular expression ^s |s $, which matches one or more space characters and replaces them with null characters string.

Summary:

No matter which method, you can easily remove the spaces before and after the string. But in actual use, we can choose which method to use according to the actual situation. If we only need to remove spaces, we can use the TrimSpace function, and if we need more flexible operations, we can use regular expressions.

The above is the detailed content of golang removes leading and trailing spaces. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!