GO 简单链式处理demo

  • 需求: 去除字符串中特定字符串(如:go),去除字符串中的所有空格,并把字符串转换为大写字母
package main

import (
	"fmt"
	"strings"
)

func processingCharacters(alist []string, string_method []func(string)string )  {

	for index, str := range alist{
		result := str
		for _, med := range string_method{
			result = med(result)
			fmt.Printf("字符处理结果:%v\n", result) // 每一个循环的字符处理结果
		}
		alist[index] = result
	}
}

func removeGo(astr string) string  {
	// 去除go字符
	result := astr
	isGo := strings.Contains(result, "go")
	if isGo {
		result = strings.Replace(result, "go", "", -1)
	}
	return result
}

func removeSpace(astr string) string  {
	// 去除所有空格
	result := astr
	ispace := strings.Contains(result," ")
	if ispace{
		result = strings.Replace(result, " ", "", -1)
	}
	return result
}

func main() {
	str_list := []string{
		"go handsome",
		"goamazing",
		" handsome go  ",
	}

	modus := []func(string)string{
		removeGo, // 去除go字符
		removeSpace, // 去除空格
		strings.ToUpper, // 转换字符为大写
	}

	processingCharacters(str_list, modus)

	fmt.Println("处理后的字符信息")
	for _,value := range str_list{
		fmt.Printf("%v\n", value)
	}

}

你可能感兴趣的:(GO)