×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Golang strings.TrimSpace() Function with Examples

Golang | strings.TrimSpace() Function: Here, we are going to learn about the TrimSpace() function of strings package with its usages, syntax, and examples.
Submitted by IncludeHelp, on August 23, 2021

strings.TrimSpace()

The TrimSpace() function is an inbuilt function of strings package which is used to get a string with all leading and trailing white space removed, as defined by Unicode. It accepts a string and returns white spaces removed string.

Syntax

func TrimSpace(str string) string

Parameters

  • str : The string in which we have to remove leading and trailing white spaces.

Return Value

The return type of TrimSpace() function is a string, it returns a string with all leading and trailing white space removed.

Example 1

// Golang program to demonstrate the
// example of strings.TrimSpace() Function

package main

import (
	"fmt"
	"strings"
)

func main() {
	fmt.Println(strings.TrimSpace("  Hello, world  "))
	fmt.Println(strings.TrimSpace("  Hello,   world  "))
	fmt.Println(strings.TrimSpace("\nHello, world\n"))
	fmt.Println(strings.TrimSpace("\r\tHello, world\r\t"))
	fmt.Println(strings.TrimSpace("\t \n \tHello, world\t\n"))
	fmt.Println(strings.TrimSpace("   Hello, world!!!"))
}

Output:

Hello, world
Hello,   world
Hello, world
Hello, world
Hello, world
Hello, world!!!

Example 2

// Golang program to demonstrate the
// example of strings.TrimSpace() Function

package main

import (
	"fmt"
	"strings"
)

func main() {
	var str string
	var result string

	str = "   Hi, there! How are you?  "
	result = strings.TrimSpace(str)
	fmt.Println("Actual string :", str)
	fmt.Println("Trimmed string:", result)

	str = "\n\n\nHi, how are you\n\n\n"
	result = strings.TrimSpace(str)
	fmt.Println("Actual string :", str)
	fmt.Println("Trimmed string:", result)

	str = "\t\rHello, world\t\r"
	result = strings.TrimSpace(str)
	fmt.Println("Actual string :", str)
	fmt.Println("Trimmed string:", result)
}

Output:

Actual string :    Hi, there! How are you?  
Trimmed string: Hi, there! How are you?
Actual string : 


Hi, how are you



Trimmed string: Hi, how are you
Actual string : 	
Hello, world	
Trimmed string: Hello, world

Golang strings Package Functions »




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.