×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Golang strings.TrimPrefix() Function with Examples

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

strings.TrimPrefix()

The TrimPrefix() function is an inbuilt function of strings package which is used to get a string without the provided leading prefix string. It accepts two parameters – a string and a prefix string and returns the string after trimming the prefix.

If the string doesn't start with the given prefix, the string is returned unchanged.

Syntax

func TrimPrefix(str, prefix string) string

Parameters

  • str : The string in which we have to remove prefix string
  • prefix : The prefix string to be trimmed.

Return Value

The return type of TrimPrefix() function is a string, it returns a string without the provided leading prefix string.

Example 1

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

package main

import (
	"fmt"
	"strings"
)

func main() {
	fmt.Println(strings.TrimPrefix("  Hello, world  ", "  Hello, "))
	fmt.Println(strings.TrimPrefix("...Hello, world...", "..."))
	fmt.Println(strings.TrimPrefix("###Hello, world!!!", "###"))
	fmt.Println(strings.TrimPrefix("Hi! World!", "Hi! "))
	fmt.Println(strings.TrimPrefix("###Hello, world!!!", "Hi! "))
}

Output:

world  
Hello, world...
Hello, world!!!
World!
###Hello, world!!!

Example 2

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

package main

import (
	"fmt"
	"strings"
)

func main() {
	var str string
	var result string

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

	str = "'Hi, how are you?"
	result = strings.TrimPrefix(str, "'Hi, ")
	fmt.Println("Actual string :", str)
	fmt.Println("Trimmed string:", result)

	str = "¡¡¡Hello, world!!!"
	result = strings.TrimPrefix(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: 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.