Menu Close

Go – TrimString Function in net/textproto package in Go

In this article, we will explore the TrimString Function in net/textproto package in Go in detail, along with examples.

Introduction:

The ‘textproto’ package in Go is part of the standard library, designed to work with text-based protocols such as HTTP and SMTP. The package provides a variety of functions to parse, read, and write text-based protocol headers. One handy function is TrimString, which trims a string by removing all leading and trailing ASCII whitespace.

In this article, we will discuss the TrimString function of the ‘textproto’ package in Go, explore its use cases, and provide a working example to demonstrate its functionality.

What is TrimString Function ?

TrimString Function in net/textproto package in Go that trims a string by removing all leading and trailing ASCII whitespace. ASCII whitespace characters include horizontal tab (‘\t’), newline (‘\n’), vertical tab (‘\v’), form feed (‘\f’), carriage return (‘\r’), and space (‘ ‘). The function is defined as follows:

Function Signature

The function signature for TrimString is as follows:

func TrimString(s string) string

TrimString accepts a single parameter ‘s’, which is the string that needs to be trimmed, and returns a new string with the leading and trailing whitespace removed.

Example

To demonstrate the use of TrimString, let’s create a simple Go program that trims a user-inputted string containing leading and trailing whitespace characters.

package main

import (
	"bufio"
	"fmt"
	"os"
	"textproto"
)

func main() {

	reader := bufio.NewReader(os.Stdin)

	fmt.Print("Enter a string with leading and trailing whitespace: ")

	input, _ := reader.ReadString('\n')

	trimmedString := textproto.TrimString(input)

	fmt.Printf("Trimmed string: '%s'\n", trimmedString)
}

In the example above, the program uses a buffered reader to read a user-inputted string and store it in the ‘input’ variable. The ‘TrimString’ function is called with the ‘input’ string, and the result is stored in the ‘trimmedString’ variable. Finally, the trimmed string is printed to the console.

Output:

Enter a string with leading and trailing whitespace:   Hello, world!    
Trimmed string: 'Hello, world!'

Conclusion

The TrimString function is a useful utility provided by the ‘textproto’ package in the Go standard library. It simplifies working with text-based protocols by trimming leading and trailing ASCII whitespace from strings. Understanding how to use this function is crucial for developers working with HTTP, SMTP, and other text-based protocols in Go.

To check more Go related articles. Pls click given below link:

https://www.techieindoor.com/category/leetcode/

https://pkg.go.dev/net/[email protected]

Posted in golang, net, packages

Leave a Reply

Your email address will not be published. Required fields are marked *