Golang之函数练习

时间:2023-02-14 03:22:00

小例题:

package main

import "fmt"

/*
函数练习,
可变参数使用 写一个函数add 支持1个或多个int相加,并返回相加结果
写一个函数concat,支持1个或多个string拼接,并返回结果
*/
func add(a int, arg ...int) int {
sum := a
for i := ; i < len(arg); i++ {
sum += arg[i]
}
return sum
} func concat(a string, arg ...string) (result string) {
result = a
for i := ; i < len(arg); i++ {
result += arg[i]
}
return
} func main() {
sum := add(, , , , , )
fmt.Println(sum)
res:=concat("hello"," ","大屌")
fmt.Println(res)
}

九九乘法表:

package main

import "fmt"
//99乘法表
func multi() {
for i := ; i < ; i++ {
for j := ; j <= i; j++ {
fmt.Printf("%d*%d=%d\t", (i + ), j+, (i+)*(j+))
}
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/ {
break
}
last := length - i -
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 >= '' && v <= '':
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\n space count:%d\n number count:%d\n others count:%d\n",wc,sc,nc,oc)
}