//处理字符串,实现大小写奇数偶数交替
package main
import(
"fmt"
"strings"
)
func main() {
str := "aBwfawjoajfWFnojfoawEWE"
result := proessLetter(str)
fmt.Printf(result)
}
func proessLetter(str string) string{
result := ""
for i,v := range str{
if i%2 == 0{
result += strings.ToUpper(string(v))
}else{
result += strings.ToLower(string(v))
}
}
return result
}
把函数当参数来使用
//处理字符串,实现大小写奇数偶数交替
package main
import(
"fmt"
"strings"
)
func main() {
str := "aBwfawjoajfWFnojfoawEWE"
//把函数当参数来调用
res := StringToCase(str,proessLetter)
fmt.Printf(res)
}
func proessLetter(str string) string{
result := ""
for i,v := range str{
if i%2 == 0{
result += strings.ToUpper(string(v))
}else{
result += strings.ToLower(string(v))
}
}
return result
}
func StringToCase(str string,myfun func(string) string) string{
return myfun(str)
}
使用type关键词自定义类型
//使用type关键词自定义类型
package main
import(
"fmt"
"strings"
)
type caseFunc func(string) string
func main() {
str := "aBwfawjoajfWFnojfoawEWE"
//把函数当参数来调用
res := StringToCase(str,proessLetter)
fmt.Printf(res)
}
func proessLetter(str string) string{
result := ""
for i,v := range str{
if i%2 == 0{
result += strings.ToUpper(string(v))
}else{
result += strings.ToLower(string(v))
}
}
return result
}
func StringToCase(str string,myfun caseFunc) string{
return myfun(str)
}
获取切片奇偶切片
package main
import "fmt"
type myfun func(int) bool
func main() {
arr := []int{1,2,5,10,12,13,15,20,22,31}
even := Filter(arr,isEven)
fmt.Println("偶数",even)
odd := Filter(arr,isOdd)
fmt.Println("奇数",odd)
}
func isEven(num int) bool{
if(num %2 == 0){
return true
}
return false
}
func isOdd(num int) bool{
if(num %2 == 0){
return false
}
return true
}
//根据函数来处理切片,实现奇偶分组
func Filter(arr []int,f myfun) []int{
var result []int
for _,value := range arr{
if f(value) {
result = append(result,value)
}
}
return result
}