小例题:
package main import "fmt" /* 函数练习, 可变参数使用 写一个函数add 支持1个或多个int相加,并返回相加结果 写一个函数concat,支持1个或多个string拼接,并返回结果 */ func add(a int, arg ...int) int { sum := a for i := 0; i < len(arg); i++ { sum += arg[i] } return sum } func concat(a string, arg ...string) (result string) { result = a for i := 0; i < len(arg); i++ { result += arg[i] } return } func main() { sum := add(10, 3, 3, 3, 3, 3) fmt.Println(sum) res:=concat("hello"," ","大屌") fmt.Println(res) }
九九乘法表:
package main import "fmt" //99乘法表 func multi() { for i := 0; i < 9; i++ { for j := 0; j <= i; j++ { fmt.Printf("%d*%d=%d ", (i + 1), j+1, (i+1)*(j+1)) } fmt.Println() } } func main() { multi() }
检测回文(中文):
package main import ( "fmt" ) func process(str string) bool { t := []rune(str) length := len(t) for i, _ := range t { if i == length/2 { break } last := length - i - 1 if t[i] != t[last] { return false } } return true } func main() { var str string fmt.Scanf("%sd", &str) if process(str) { fmt.Println("yes") } else { fmt.Println("no") } }
统计一段字符串,中文,字符,数字,空格,出现的次数:
package main import ( "bufio" "fmt" "os" ) func count(str string) (wordCount, spaceCount, numberCount, otherCount int) { t := []rune(str) for _, v := range t { switch { case v >= 'a' && v <= 'z': fallthrough case v >= 'A' && v <= 'Z': //golang里面++是语句,不能写成表达式 wordCount++ case v == ' ': spaceCount++ case v >= '0' && v <= '9': numberCount++ default: otherCount++ } } return } func main() { reader := bufio.NewReader(os.Stdin) result, _, err := reader.ReadLine() //如果错误不为空,说明有错,就报错 if err != nil { fmt.Println("read from console err:", err) return } wc,sc,nc,oc:=count(string(result)) fmt.Printf("word Count:%d space count:%d number count:%d others count:%d ",wc,sc,nc,oc) }