编写golang程序实现字符串反转,例如给定字符串 "string",输出结果应该为 "gnirts"
时间: 2023-10-22 20:24:01 浏览: 48
可以通过遍历字符串,将每个字符倒序添加到一个新的字符串中实现字符串反转。以下是一个简单的golang程序实现:
```go
package main
import "fmt"
func reverseString(s string) string {
var reversed string
for i := len(s)-1; i >= 0; i-- {
reversed += string(s[i])
}
return reversed
}
func main() {
input := "string"
output := reverseString(input)
fmt.Println(output) // gnirts
}
```
该程序定义了一个 `reverseString` 函数,该函数接受一个字符串作为输入,并返回反转后的字符串。在 `reverseString` 函数中,我们使用一个 for 循环遍历原始字符串并将其倒序添加到一个新的字符串中。最后,我们从 `main` 函数调用 `reverseString` 函数并打印输出结果。
相关问题
编写程序,统计字符串中每个字符的出现次数 golang
以下是一个简单的程序,可以统计一个字符串中每个字符的出现次数:
```
package main
import (
"fmt"
)
func countChars(s string) map[rune]int {
counts := make(map[rune]int)
for _, c := range s {
counts[c]++
}
return counts
}
func main() {
s := "Hello, world!"
counts := countChars(s)
for c, count := range counts {
fmt.Printf("%c: %d\n", c, count)
}
}
```
在这个程序中,`countChars` 函数接受一个字符串作为参数,并返回一个 `map`,其中每个字符都是一个键,对应的值是该字符在字符串中出现的次数。该函数使用一个 `for` 循环遍历字符串的每个字符,并在 `counts` 映射中增加对应的计数器。最后,`counts` 映射被返回给调用者。
在 `main` 函数中,我们定义了一个字符串 `s`,并调用 `countChars` 函数来获取字符计数器的映射。然后,我们使用一个 `for` 循环遍历 `counts` 映射,并打印每个字符以及它在字符串中出现的次数。注意,我们使用 `%c` 格式化字符串来打印字符,而不是使用 `%s`,因为 `%c` 可以打印 Unicode 字符。
golang 实现字符串枚举
Golang 中没有内置的字符串枚举类型,但可以通过定义常量来模拟字符串枚举。下面是一个例子:
```go
package main
import "fmt"
type Fruit string
const (
Apple Fruit = "apple"
Banana Fruit = "banana"
Orange Fruit = "orange"
)
func main() {
fmt.Println(Apple)
fmt.Println(Banana)
fmt.Println(Orange)
}
```
在上面的例子中,`Fruit` 是一个字符串类型,我们通过定义常量 `Apple`、`Banana` 和 `Orange` 来模拟字符串枚举。在 `main` 函数中,我们可以像使用普通字符串一样使用这些常量。
注意,由于 Golang 中的常量是无类型的,因此需要使用 `Fruit` 类型来指定常量的类型。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)