題目

Given a valid (IPv4) IP address, return a defanged version of that IP address.

A defanged IP address replaces every period “.” with “[.]”.

## Example 1:

Input: address = "1.1.1.1"
Output: "1[.]1[.]1[.]1"

Example 2:

Input: address = "255.100.50.0"
Output: "255[.]100[.]50[.]0"
  • 題意: 將字串.替換成[.]就好了

解法

import (
	"strings"
)

func defangIPaddr(address string) string {
	return strings.Replace(address, ".", "[.]", -1)
}
  • 加個測試,看看結果是不是如預期
import (
	"github.com/stretchr/testify/assert"
	"testing"
)

func Test_defangIPaddr(t *testing.T) {
	address := "1.1.1.1"
	assert.Equal(t, "1[.]1[.]1[.]1", defangIPaddr(address))
}

參考連結