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?
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.
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.
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.
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.
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 +
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+
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With