The Wayback Machine - https://web.archive.org/web/20240927172910/https://www.geeksforgeeks.org/how-to-trim-a-string-in-golang/
Open In App

How to Trim a String in Golang?

Last Updated : 26 Aug, 2019
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In Go language, strings are different from other languages like Java, C++, Python, etc. It is a sequence of variable-width characters where each and every character is represented by one or more bytes using UTF-8 Encoding. You can trim a string in different ways using the following list of functions. All these functions are defined under strings package, so you have to import strings package in your program to access these functions.

1. Trim: This function is used to trim the string all the leading and trailing Unicode code points which are specified in this function.

Syntax:

func Trim(str string, cutstr string) string

Here, str represent the current string and cutstr represents the elements which you want to trim in the given string.

Example:




// Go program to illustrate 
// how to trim a string
package main
  
import (
    "fmt"
    "strings"
)
  
// Main method
func main() {
  
    // Creating and initializing string
    // Using shorthand declaration
    str1 := "!!Welcome to GeeksforGeeks !!"
    str2 := "@@This is the tutorial of Golang$$"
  
    // Displaying strings
    fmt.Println("Strings before trimming:")
    fmt.Println("String 1: ", str1)
    fmt.Println("String 2:", str2)
  
    // Trimming the given strings
    // Using Trim() function
    res1 := strings.Trim(str1, "!")
    res2 := strings.Trim(str2, "@$")
  
    // Displaying the results
    fmt.Println("\nStrings after trimming:")
    fmt.Println("Result 1: ", res1)
    fmt.Println("Result 2:", res2)
}


Output:

Strings before trimming:
String 1:  !!Welcome to GeeksforGeeks !!
String 2: @@This is the tutorial of Golang$$

Strings after trimming:
Result 1:  Welcome to GeeksforGeeks 
Result 2: This is the tutorial of Golang

 

2. TrimLeft: This function is used to trim the left-hand side(specified in the function) Unicode code points of the string.

Syntax:

func TrimLeft(str string, cutstr string) string

Here, str represent the current string and cutstr represents the left-hand side elements which you want to trim in the given string.

Example:




// Go program to illustrate how to
// trim left-hand side elements
// from the string
package main
  
import (
    "fmt"
    "strings"
)
  
// Main method
func main() {
  
    // Creating and initializing string
    // Using shorthand declaration
    str1 := "!!Welcome to GeeksforGeeks **"
    str2 := "@@This is the tutorial of Golang$$"
  
    // Displaying strings
    fmt.Println("Strings before trimming:")
    fmt.Println("String 1: ", str1)
    fmt.Println("String 2:", str2)
  
    // Trimming the given strings
    // Using TrimLeft() function
    res1 := strings.TrimLeft(str1, "!*")
    res2 := strings.TrimLeft(str2, "@")
  
    // Displaying the results
    fmt.Println("\nStrings after trimming:")
    fmt.Println("Result 1: ", res1)
    fmt.Println("Result 2:", res2)
}


Output:

Strings before trimming:
String 1:  !!Welcome to GeeksforGeeks **
String 2: @@This is the tutorial of Golang$$

Strings after trimming:
Result 1:  Welcome to GeeksforGeeks **
Result 2: This is the tutorial of Golang$$

 

3. TrimRight: This function is used to trim the right-hand side(specified in the function) Unicode code points of the string.

Syntax:

func TrimRight(str string, cutstr string) string

Here, str represent the current string and cutstr represents the right-hand side elements which you want to trim in the given string.

Example:




// Go program to illustrate how to
// trim right-hand side elements
// from the string
package main
  
import (
    "fmt"
    "strings"
)
  
// Main method
func main() {
  
    // Creating and initializing the
    // string using shorthand declaration
    str1 := "!!Welcome to GeeksforGeeks **"
    str2 := "@@This is the tutorial of Golang$$"
  
    // Displaying strings
    fmt.Println("Strings before trimming:")
    fmt.Println("String 1: ", str1)
    fmt.Println("String 2:", str2)
  
    // Trimming the given strings
    // Using TrimRight() function
    res1 := strings.TrimRight(str1, "!*")
    res2 := strings.TrimRight(str2, "$")
  
    // Displaying the results
    fmt.Println("\nStrings after trimming:")
    fmt.Println("Result 1: ", res1)
    fmt.Println("Result 2:", res2)
}


Output:

Strings before trimming:
String 1:  !!Welcome to GeeksforGeeks **
String 2: @@This is the tutorial of Golang$$

Strings after trimming:
Result 1:  !!Welcome to GeeksforGeeks 
Result 2: @@This is the tutorial of Golang

 

4. TrimSpace: This function is used to trim all the leading and trailing white space from the specified string.

Syntax:

func TrimSpace(str string) string

Example:




// Go program to illustrate how to
// trim white space from the string
package main
  
import (
    "fmt"
    "strings"
)
  
// Main method
func main() {
  
    // Creating and initializing string
    // Using shorthand declaration
    str1 := "   **Welcome to GeeksforGeeks**   "
    str2 := "  ##This is the tutorial of Golang##  "
  
    // Displaying strings
    fmt.Println("Strings before trimming:")
    fmt.Println(str1, str2)
  
    // Trimming white space from the given strings
    // Using TrimSpace() function
    res1 := strings.TrimSpace(str1)
    res2 := strings.TrimSpace(str2)
  
    // Displaying the results
    fmt.Println("\nStrings after trimming:")
    fmt.Println(res1, res2)
}


Output:

Strings before trimming:
   **Welcome to GeeksforGeeks**      ##This is the tutorial of Golang##  

Strings after trimming:
**Welcome to GeeksforGeeks** ##This is the tutorial of Golang##

 

5. TrimSuffix: This method is used to trim the trailing suffix string from the given string. If the given string does not contain the specified suffix string, then this function returns the original string without any change.

Syntax:

func TrimSuffix(str, suffstr string) string

Here, str represents the original string and suffstr represent the suffix string.

Example:




// Go program to illustrate how to
// trim a suffix string from the
// given string
package main
  
import (
    "fmt"
    "strings"
)
  
// Main method
func main() {
  
    // Creating and initializing string
    // Using shorthand declaration
    str1 := "Welcome, GeeksforGeeks"
    str2 := "This is the, tutorial of Golang"
  
    // Displaying strings
    fmt.Println("Strings before trimming:")
    fmt.Println("String 1: ", str1)
    fmt.Println("String 2:", str2)
  
    // Trimming suffix string from the given strings
    // Using TrimSuffix() function
    res1 := strings.TrimSuffix(str1, "GeeksforGeeks")
    res2 := strings.TrimSuffix(str2, "Hello")
  
    // Displaying the results
    fmt.Println("\nStrings after trimming:")
    fmt.Println("Result 1: ", res1)
    fmt.Println("Result 2:", res2)
}


Output:

Strings before trimming:
String 1:  Welcome, GeeksforGeeks
String 2: This is the, tutorial of Golang

Strings after trimming:
Result 1:  Welcome, 
Result 2: This is the, tutorial of Golang

 

6. TrimPrefix: This method is used to trim the leading prefix string from the given string. If the given string does not contain the specified prefix string, then this function returns the original string without any change.

Syntax:

func TrimPrefix(str, suffstr string) string

Here, str represents the original string and suffstr represent the prefix string.

Example:




// Go program to illustrate how to
// trim the prefix string from the
// given string
package main
  
import (
    "fmt"
    "strings"
)
  
// Main method
func main() {
  
    // Creating and initializing string
    // Using shorthand declaration
    str1 := "Welcome, GeeksforGeeks"
    str2 := "This is the, tutorial of Golang"
  
    // Displaying strings
    fmt.Println("Strings before trimming:")
    fmt.Println("String 1: ", str1)
    fmt.Println("String 2: ", str2)
  
    // Trimming prefix string from the given strings
    // Using TrimPrefix() function
    res1 := strings.TrimPrefix(str1, "Welcome")
    res2 := strings.TrimPrefix(str2, "Hello")
  
    // Displaying the results
    fmt.Println("\nStrings after trimming:")
    fmt.Println("Result 1: ", res1)
    fmt.Println("Result 2: ", res2)
}


Output:

Strings before trimming:
String 1:  Welcome, GeeksforGeeks
String 2:  This is the, tutorial of Golang

Strings after trimming:
Result 1:  , GeeksforGeeks
Result 2:  This is the, tutorial of Golang


Previous Article
Next Article

Similar Reads

How to trim prefix from the slice of bytes in Golang?
In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice. In the Go slice of bytes, you are allowed to trim prefix from the given slice usin
3 min read
How to trim suffix from the slice of bytes in Golang?
In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice. In the Go slice of bytes, you are allowed to trim suffix from the given slice usin
3 min read
How to trim a slice of bytes in Golang?
In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice. In the Go slice of bytes, you are allowed to trim all the leading and trailing UTF
4 min read
How to trim white spaces from the slice of bytes in Golang?
In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice. In the Go slice of bytes, you are allowed to trim all the leading and trailing whi
3 min read
How to trim left-hand side of a slice of bytes in Golang?
In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice. In the Go slice of bytes, you are allowed to trim all the starting UTF-8-encoded c
3 min read
How to trim right-hand side of a slice of bytes in Golang?
In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice. In the Go slice of bytes, you are allowed to trim all the ending UTF-8-encoded cod
3 min read
Converting a string variable into Boolean, Integer or Float type in Golang
Various types of string conversions are needed while performing tasks in Golang. Package strconv is imported to perform conversions to and from string. String to Boolean Conversion ParseBool is used to convert string to boolean value. It accepts 1, t, T, TRUE, true, True as true and 0, f, F, FALSE, false, False as false. Any other value returns an
3 min read
How to convert a string in uppercase in Golang?
In Go language, strings are different from other languages like Java, C++, Python, etc. It is a sequence of variable-width characters where each and every character is represented by one or more bytes using UTF-8 Encoding. In Go string, you are allowed to convert a string in the uppercase using the following functions. All these functions are defin
3 min read
How to convert a string in lower case in Golang?
In Go language, strings are different from other languages like Java, C++, Python, etc. It is a sequence of variable-width characters where each and every character is represented by one or more bytes using UTF-8 Encoding. In Go string, you are allowed to convert a string in the lowercase using ToLower() function. This function returns a copy of th
2 min read
Check if the given characters is present in Golang String
In Go language, strings are different from other languages like Java, C++, Python, etc. It is a sequence of variable-width characters where each and every character is represented by one or more bytes using UTF-8 Encoding. In Go strings, you are allowed to check the given characters present in the string using the given functions. These functions a
3 min read
How to Replace Characters in Golang String?
In Go language, strings are different from other languages like Java, C++, Python, etc. It is a sequence of variable-width characters where each and every character is represented by one or more bytes using UTF-8 Encoding. In Go strings, you are allowed to replace characters in the given string using the given functions. These functions are defined
4 min read
Repeating a String for Specific Number of Times in Golang
In Go language, strings are different from other languages like Java, C++, Python, etc. It is a sequence of variable-width characters where each and every character is represented by one or more bytes using UTF-8 Encoding. You are allowed to repeat a string of for a specific number of times with the help of the Repeat() Function. This method return
3 min read
How to find the index value of specified string in Golang?
In Go language, strings are different from other languages like Java, C++, Python, etc. It is a sequence of variable-width characters where each and every character is represented by one or more bytes using UTF-8 Encoding. In Go strings, you can find the first index value of the specified string from the original string using the following function
4 min read
How to find the last index value of specified string in Golang?
In Go language, strings are different from other languages like Java, C++, Python, etc. It is a sequence of variable-width characters where each and every character is represented by one or more bytes using UTF-8 Encoding. In Go strings, you can find the last index value of the specified string from the original string using the following functions
4 min read
How to Count the Number of Repeated Characters in a Golang String?
In Go language, strings are different from other languages like Java, C++, Python, etc. It is a sequence of variable-width characters where each and every character is represented by one or more bytes using UTF-8 Encoding. In Go string, you can count some specific Unicode code points or the number of non-overlapping instances of costr (Repeated Cha
2 min read
Check if the String starts with specified prefix in Golang
In Go language, strings are different from other languages like Java, C++, Python, etc. It is a sequence of variable-width characters where each and every character is represented by one or more bytes using UTF-8 Encoding. In Golang strings, you can check whether the string begins with the specified prefix or not with the help of HasPrefix() functi
2 min read
Check if the String ends with specified suffix in Golang
In Go language, strings are different from other languages like Java, C++, Python, etc. It is a sequence of variable-width characters where each and every character is represented by one or more bytes using UTF-8 Encoding. In Go strings, you can check whether the string ends with the specified suffix or not with the help of HasSuffix() function. Th
2 min read
How to check String for equality under Unicode case folding in Golang?
In Go language, strings are different from other languages like Java, C++, Python, etc. It is a sequence of variable-width characters where each and every character is represented by one or more bytes using UTF-8 Encoding. In Go strings, you are allowed to compare two strings with each other without any error even if they are written in different c
3 min read
Golang | How to find the index of rune in the string?
In Go language, strings are different from other languages like Java, C++, Python, etc. It is a sequence of variable-width characters where each and every character is represented by one or more bytes using UTF-8 Encoding. In the Go strings, you can also find the first index of the specified rune in the given string using IndexRune() function. This
3 min read
How to check the specified rune in Golang String?
In Go language, strings are different from other languages like Java, C++, Python, etc. It is a sequence of variable-width characters where each and every character is represented by one or more bytes using UTF-8 Encoding. In the Go strings, you are allowed to check the given string contain the specified rune in it using ContainsRune() function. Th
3 min read
Searching an element of string type in Golang slice
In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice. In the Go slice, you can search an element of string type in the given slice of st
3 min read
Golang | Checking the string for the specified regular expression
A regular expression is a sequence of characters which define a search pattern. Go language support regular expressions. A regular expression is used for parsing, filtering, validating, and extracting meaningful information from large text, like logs, the output generated from other programs, etc. In Go regexp, you are allowed to check whether the
3 min read
Golang | Splitting the string after the specified separator
In Go language, strings are different from other languages like Java, C++, Python, etc. It is a sequence of variable-width characters where each and every character is represented by one or more bytes using UTF-8 Encoding. In the Go strings, you are allowed to split the string after the specified separator using a SplitN() function. This function s
3 min read
Golang | Creating a string that contains regexp metacharacters
A regular expression is a sequence of characters which define a search pattern. Go language support regular expressions. A regular expression is used for parsing, filtering, validating, and extracting meaningful information from large text, like logs, the output generated from other programs, etc. In Go regexp, you are allowed to create a string th
2 min read
Golang | Extracting a Regular Expression from the String
A regular expression is a sequence of characters which define a search pattern. Go language support regular expressions. A regular expression is used for parsing, filtering, validating, and extracting meaningful information from large text, like logs, the output generated from other programs, etc. In Go regexp, you are allowed to extract a regular
2 min read
Golang | Extracting all the Regular Expression from the String
A regular expression is a sequence of characters which define a search pattern. Go language support regular expressions. A regular expression is used for parsing, filtering, validating, and extracting meaningful information from large text, like logs, the output generated from other programs, etc. In Go regexp, you are allowed to find all the regul
2 min read
Golang | Finding Index of the Regular Expression present in String
A regular expression is a sequence of characters which define a search pattern. Go language support regular expressions. A regular expression is used for parsing, filtering, validating, and extracting meaningful information from large text, like logs, the output generated from other programs, etc. In Go regexp, you are allowed to find the leftmost
2 min read
Golang | Replacing all String which Matches with Regular Expression
A regular expression is a sequence of characters which define a search pattern. Go language support regular expressions. A regular expression is used for parsing, filtering, validating, and extracting meaningful information from large text, like logs, the output generated from other programs, etc. In Go regexp, you are allowed to replace original s
2 min read
time.String() Function in Golang With Examples
In Go language, time packages supplies functionality for determining as well as viewing time. The String() function in Go language is used to find a string that represents the duration formats as "24h6m0.7s". Here, the foremost zero units are deleted. And the stated duration with less than one-second format will use a smaller unit, for example, mil
2 min read
time.Month.String() Function in Golang With Examples
In Go language, time packages supplies functionality for determining as well as viewing time. The Month.String() function in Go language is used to find the English name of the month. Moreover, this function is defined under the time package. Here, you need to import the "time" package in order to use these functions. Syntax: func (m Month) String(
2 min read