In the article, we will see how to trim a string before a specific character to extract the portion of a string before the particular character.

In Golang, we can do all types of operations on strings easily using the strings package which is a part of Golang’s standard library.

The strings package in Golang provides an API called Index() which allows us to get the position of a specific character.

How to trim a string:

The easiest way to trim a string is to extract the position of the character using the strings.Index() and extract the substring from the start of the original string up to the target character index.

Following is the example:

package main

import (
	"fmt"
	"strings"
)

func main() {
	str := "Hello, World!"
	char := ","

	index := strings.Index(str, char)
	if index == -1 {
		fmt.Printf("Character '%s' not found in the string.\n", char)
		return
	}

	trimmedStr := str[:index]

	fmt.Println("Original String:", str)
	fmt.Println("Trimmed String:", trimmedStr)
}

In the above example, We used the strings.Index() function to find the index of the first occurrence of the target character in the string. It returns the index of the first occurrence of the character and -1 if the character is not found.

If the target character is found, we extract the substring from the start of the original string str up to the index of the target character using slicing. The result is then stored in the variable trimmedStr.

Following is the output of the above example:

Original String: Hello, World!
Trimmed String: Hello

Categorized in:

Tagged in: