Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,955 questions

51,897 answers

573 users

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 removeLastN(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 := removeLastN(text, "xyz", 3)
    fmt.Println(result)

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



/*
run:

abc xyz  abc abc abc
abc xyz abc abc abc

*/

 



answered 3 hours ago by avibootz

Related questions

...