Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove the last character of a string in Golang?

Tags:

string

go

I want to remove the very last character of a string, but before I do so I want to check if the last character is a "+". How can this be done?

like image 755
Micheal Perr Avatar asked Dec 31 '11 17:12

Micheal Perr


People also ask

How do you remove part of a string in Golang?

To replace a substring in string with a new value in Go programming, we can use either Replace function or ReplaceAll function of the strings package. Replace function replaces only specified N occurrences of the substring, while ReplaceAll function replaces all the occurrences of given substring with the new value.

How do I remove the last 3 characters from a string?

To remove the last three characters from the string you can use string. Substring(Int32, Int32) and give it the starting index 0 and end index three less than the string length. It will get the substring before last three characters.

How do you get rid of a character in a string?

We can use string replace() function to replace a character with a new character. If we provide an empty string as the second argument, then the character will get removed from the string.

Does Golang have a prefix?

In Golang strings, you can check whether the string begins with the specified prefix or not with the help of HasPrefix() function. This function returns true if the given string starts with the specified prefix and return false if the given string does not start with the specified prefix.


2 Answers

Here are several ways to remove trailing plus sign(s).

package main  import (     "fmt"     "strings" )  func TrimSuffix(s, suffix string) string {     if strings.HasSuffix(s, suffix) {         s = s[:len(s)-len(suffix)]     }     return s }  func main() {     s := "a string ++"     fmt.Println("s: ", s)      // Trim one trailing '+'.     s1 := s     if last := len(s1) - 1; last >= 0 && s1[last] == '+' {         s1 = s1[:last]     }     fmt.Println("s1:", s1)      // Trim all trailing '+'.     s2 := s     s2 = strings.TrimRight(s2, "+")     fmt.Println("s2:", s2)      // Trim suffix "+".     s3 := s     s3 = TrimSuffix(s3, "+")     fmt.Println("s3:", s3) } 

Output:

s:  a string ++ s1: a string + s2: a string  s3: a string + 
like image 164
peterSO Avatar answered Oct 06 '22 12:10

peterSO


Based on the answer of @KarthikGR the following example was added:

https://play.golang.org/p/ekDeT02ZXoq

package main  import (     "fmt"     "strings" )  func main() {     fmt.Println(strings.TrimSuffix("Foo++", "+")) } 

returns:

Foo+ 
like image 23
030 Avatar answered Oct 06 '22 13:10

030