How to remove the last n occurrences of a substring in a string in Go

1 Answer

0 votes
package main

import (
    "fmt"
    "strings"
)

// Remove last n occurrences of a substring
func removeLastNOccurrences(s, sub string, n int) string {
    var positions []int
    pos := strings.Index(s, sub)

    // Find all occurrences
    for pos != -1 {
        positions = append(positions, pos)
        pos = strings.Index(s[pos+len(sub):], sub)
        if pos != -1 {
            pos += positions[len(positions)-1] + len(sub)
        }
    }

    // Remove from the end
    for i := len(positions) - 1; i >= 0 && n > 0; i-- {
        start := positions[i]
        s = s[:start] + s[start+len(sub):]
        n--
    }

    return s
}

// Remove extra spaces (collapse multiple spaces, trim ends)
func removeExtraSpaces(s string) string {
    parts := strings.Fields(s)
    return strings.Join(parts, " ")
}

func main() {
    text := "abc xyz xyz abc xyzabcxyz abc"

    result := removeLastNOccurrences(text, "xyz", 3)
    fmt.Println(result)

    cleaned := removeExtraSpaces(result)
    fmt.Println(cleaned)
}



/*
run:

abc xyz  abc abc abc
abc xyz abc abc abc

*/

 



answered Feb 16 by avibootz
edited Feb 16 by avibootz

Related questions

...