首页  >  文章  >  后端开发  >  如何在 Golang 中删除字符串中的重复空格和空格?

如何在 Golang 中删除字符串中的重复空格和空格?

Barbara Streisand
Barbara Streisand原创
2024-11-15 06:01:02649浏览

How to Remove Duplicated Spaces and Whitespace from Strings in Golang?

Removing Duplicated Spaces and Whitespace from Strings in Golang

To remove both leading/trailing whitespace and redundant spaces from a string in Golang, you can utilize the strings package.

  1. Removing Leading/Trailing Whitespace:

The strings.TrimSpace() function removes leading and trailing whitespace, including new-line characters and null characters.

trimmedString := strings.TrimSpace(originalString)
  1. Removing Redundant Spaces:

To remove redundant spaces, you can use strings.Fields(). This function splits a string on whitespace characters, resulting in a slice of substrings.

formattedString := strings.Join(strings.Fields(originalString), " ")

Handling International Space Characters:

To handle international space characters, you can use unicode support. The following code uses the unicode.IsSpace() function to check for various whitespace characters:

func standardizeSpacesUnicode(s string) string {
    var buffer bytes.Buffer
    for _, r := range s {
        if unicode.IsSpace(r) {
            if buffer.Len() == 0 || buffer.Bytes()[buffer.Len()-1] != ' ' {
                buffer.WriteRune(r)
            }
        } else {
            buffer.WriteRune(r)
        }
    }
    return buffer.String()
}

Example Usage:

package main

import (
    "fmt"
    "strings"
)

func main() {
    tests := []string{
        " Hello,   World  ! ",
        " Hello,\tWorld ! ",
        " \t\n\t Hello,\tWorld\n!\n\t",
        "你好,世界!", // Unicode test
    }

    for _, test := range tests {
        trimmed := strings.TrimSpace(test)
        formatted := strings.Join(strings.Fields(test), " ")
        standardizedUnicode := standardizeSpacesUnicode(test)

        fmt.Println("Original:", test)
        fmt.Println("Trimmed:", trimmed)
        fmt.Println("Formatted:", formatted)
        fmt.Println("Standardized Unicode:", standardizedUnicode)
        fmt.Println()
    }

}

Output:

Original:  Hello,   World  !
Trimmed:  Hello, World !
Formatted:  Hello World !
Standardized Unicode: Hello World !

Original:  Hello,\tWorld !
Trimmed:  Hello, World !
Formatted:  Hello World !
Standardized Unicode: Hello World !

Original:   \t\n\t Hello,\tWorld\n!\n\t
Trimmed:  Hello, World!
Formatted:  Hello World!
Standardized Unicode: Hello World!

Original:  你好,世界!
Trimmed:  你好,世界!
Formatted:  你好 世界!
Standardized Unicode: 你好 世界!

以上是如何在 Golang 中删除字符串中的重复空格和空格?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn