How to remove characters present in first string from the second string in Go

2 Answers

0 votes
package main

import (
	"fmt"
)

// removeCharacters removes all characters from source
// that appear in charsToRemove.
func removeCharacters(source, charsToRemove string) string {
	// Build a lookup set.
	forbidden := make(map[rune]struct{})

	for _, ch := range charsToRemove {
		forbidden[ch] = struct{}{}
	}

	// Build the filtered result.
	result := make([]rune, 0, len(source))

	for _, ch := range source {
		if _, exists := forbidden[ch]; !exists {
			result = append(result, ch)
		}
	}

	return string(result)
}

func main() {
	first := "programming language"
	second := "rogy"

	result := removeCharacters(second, first)

	fmt.Printf("First : %q\n", first)
	fmt.Printf("Second: %q\n", second)
	fmt.Printf("Result: %q\n", result)
}



/*
run:

First : "programming language"
Second: "rogy"
Result: "y"

*/

 



answered Oct 4 by avibootz
0 votes
package main

import (
	"fmt"
)

// removeCharacters removes all characters from source
// that appear in charsToRemove.
func removeCharacters(source, charsToRemove string) string {
	forbidden := make(map[rune]struct{})

	for _, ch := range charsToRemove {
		forbidden[ch] = struct{}{}
	}

	var result []rune

	for _, ch := range source {
		if _, found := forbidden[ch]; !found {
			result = append(result, ch)
		}
	}

	return string(result)
}

func main() {
	first := "programming language"
	second := "rogy"

	result := removeCharacters(second, first)

	fmt.Printf("First : %q\n", first)
	fmt.Printf("Second: %q\n", second)
	fmt.Printf("Result: %q\n", result)
}



/*
run:

First : "programming language"
Second: "rogy"
Result: "y"

*/

 



answered Oct 4 by avibootz

Related questions

...