strings.Map() Golang中的函數用於返回給定字符串的字符串副本,該字符串的所有字符均根據映射函數進行了修改。如果映射返回負值,則將字符從字符串中刪除,並且不進行替換。
因此,無論何時用戶想要更改某個字符串,他都可以使用字符串。Map()函數。它用user-desired字符替換字符串的字符。如果需要屏蔽某些字符,包括數字和空格,則可以使用此函數。
用法:
func Map(mapping func(rune) rune, s string) string
映射func(rune)符文參數定義需要替換原始字符的字符,而s參數則定義用戶輸入的原始字符串。
範例1:
// Golang program to illustrate
// the strings.Map() Function
package main
import (
"fmt";
"strings"
)
func main() {
modified:= func(r rune) rune {
if r == 'e' {
return '@'
}
return r
}
input:= "Hello, Welcome to GeeksforGeeks"
fmt.Println(input)
// using the function
result:= strings.Map(modified, input)
fmt.Println(result)
}
輸出:
Hello, Welcome to GeeksforGeeks H@llo, W@lcom@ to G@@ksforG@@ks
說明:在上麵的示例中,我們使用strings.Map()函數來修改字符串。我們定義了一個名為“modified”的變量,該變量將字符串中的字符‘e’替換為符號“ @”。另一個名為“input”的變量采用需要轉換的輸入字符串。
範例2:strings.Map()函數還可用於刪除字符串中的單詞之間的空格。
// Golang program to illustrate
// the strings.Map() Function
package main
import (
"fmt";
"strings"
)
func main() {
transformed:= func(r rune) rune {
if r == ' ' {
return 0
}
return r
}
input:= "GeeksforGeeks is a computer science portal."
fmt.Println(input)
// using the function
output:= strings.Map(transformed, input)
fmt.Println(output)
}
輸出:
GeeksforGeeks is a computer science portal. GeeksforGeeksisacomputerscienceportal.
說明:在上麵的示例中,我們使用strings.Map()函數刪除字符串之間的空格。我們定義了一個名為“transformed”的變量,該變量消除了字符串中的空格“”。這是通過在空格處返回0來完成的。另一個名為“input”的變量采用一個輸入字符串,該字符串的in-between空間需要刪除。
相關用法
- Golang math.Lgamma()用法及代碼示例
- Golang math.Float64bits()用法及代碼示例
- Golang atomic.AddInt64()用法及代碼示例
- Golang atomic.StoreInt64()用法及代碼示例
- Golang reflect.FieldByIndex()用法及代碼示例
- Golang string.Contains用法及代碼示例
- Golang bits.Sub()用法及代碼示例
- Golang io.PipeWriter.CloseWithError()用法及代碼示例
- Golang time.Round()用法及代碼示例
- Golang reflect.AppendSlice()用法及代碼示例
- Golang reflect.ChanOf()用法及代碼示例
- Golang flag.Bool()用法及代碼示例
- Golang time.Sleep()用法及代碼示例
- Golang time.Time.Year()用法及代碼示例
- Golang reflect.DeepEqual()用法及代碼示例
- Golang reflect.Indirect()用法及代碼示例
- Golang reflect.CanAddr()用法及代碼示例
- Golang reflect.CanInterface()用法及代碼示例
- Golang reflect.CanSet()用法及代碼示例
- Golang reflect.Cap()用法及代碼示例
注:本文由純淨天空篩選整理自preetikagupta8171大神的英文原創作品 strings.Map() Function in Golang With Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。