Welcome To Golang By Example

Menu
  • Home
  • Blog
  • Contact Us
  • Support this website
Menu

Trim leading and trailing whitespaces from a string in Go (Golang)

Posted on March 11, 2020March 11, 2020 by admin

Table of Contents

  • Overview
  • Code:

Overview

In GO string are UTF-8 encoded. strings package of GO provides a TrimSpace method that can be used to remove the leading and trailing whitespaces. Also, note that this function returns the copy of the string.

Below is the signature of the function

func TrimSpace(s string) string

Let’s look at the working code

Code:

package main

import (
    "fmt"
    "strings"
)

func main() {
    //This will output removed
    res := strings.TrimSpace(" test  ")
    fmt.Println(res)

    res = strings.TrimSpace(" This is test  ")
    fmt.Println(res)
}

Output:

test
This is test
Follow @golangbyexample

Popular Articles

Golang Comprehensive Tutorial Series

All Design Patterns in Go (Golang)

Slice in golang

Variables in Go (Golang) – Complete Guide

OOP: Inheritance in GOLANG complete guide

Using Context Package in GO (Golang) – Complete Guide

All data types in Golang with examples

Understanding time and date in Go (Golang) – Complete Guide

©2025 Welcome To Golang By Example | Design: Newspaperly WordPress Theme