To remove a substring from a string at a specific index in Go, you can use string concatenation and substrings manipulation. Here's an example:
main.go364 chars14 lines
In this example, we define a function removeSubstringAtIndex
that takes in a string s
, an integer index idx
, and a substring substr
. The function checks if the index is within range of the input string and returns s
if it's out of bounds.
If the index is valid, the function concatenates the substring before the index s[:idx]
with the truncated string after the index where the substring to be removed will be replaced by an empty string strings.Replace(s[idx:], substr, "", 1)
. The 1
parameter in Replace
specifies the maximum number of replacements to be made.
We then test this function by passing in an example s
, idx
, and substr
values and print the resulting string to the console.
gistlibby LogSnag