How to determine whether the end of a string is a specified character in Golang

WBOY
Release: 2024-03-13 10:24:04
Original
809 people have browsed it

How to determine whether the end of a string is a specified character in Golang

Title: How to determine whether the end of a string is a specified character in Golang

In Golang, you can determine whether the end of a string is a specified character by using the strings package HasSuffix function to achieve. This function can help us quickly determine whether a string ends with a specific suffix, thus facilitating string processing and judgment operations.

Let's look at some code examples to demonstrate how to use the HasSuffix function in Golang to determine whether the end of a string is a specified character.

package main

import (
    "fmt"
    "strings"
)

func main() {
    str := "Hello, World!"

    // 判断字符串结尾是否为指定字符
    if strings.HasSuffix(str, "!") {
        fmt.Println("字符串结尾为感叹号!")
    } else {
        fmt.Println("字符串结尾不是感叹号!")
    }

    // 判断字符串结尾是否为指定字符集合的其中一个
    suffixes := []string{".", "!", "?"}
    for _, suffix := range suffixes {
        if strings.HasSuffix(str, suffix) {
            fmt.Printf("字符串结尾为%s
", suffix)
        }
    }
}
Copy after login

In the above code example, we first define a string str as "Hello, World!", and then use the HasSuffix function to determine whether the end of the string is the specified character "!". Then we defined a string slice suffixes, which contains three suffix characters ".", "!" and "?", and then used a loop to determine whether the end of the string is any of these characters.

Through the above code example, we can clearly understand how to use the HasSuffix function in Golang to determine whether the end of a string is a specified character. This method is simple, efficient and easy to master, and is very suitable for use in daily string processing.

The above is the detailed content of How to determine whether the end of a string is a specified character in Golang. 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!