Go语言程序:使用索引从字符串中获取字符


在 Go 语言中,有多种方法可以使用索引从字符串中获取字符。本文将介绍使用外部函数和 Go 语言内置函数的方法。

方法 1:使用用户自定义函数

在这种方法中,我们创建的函数将接收需要确定其字符的字符串以及字符串的整数类型索引作为参数,并返回该索引处字符串的字符。

算法

  • 步骤 1 − 首先,我们需要导入 fmt 包。

  • 步骤 2 − 然后,创建一个函数,该函数将接收需要确定其字符的字符串以及索引作为参数。

  • 步骤 3 − 开始 main() 函数。

  • 步骤 4 − 在 main() 函数内部,初始化一个字符串类型的变量并为其赋值。

  • 步骤 5 − 在屏幕上打印该变量。

  • 步骤 6 − 初始化一个 int 类型的变量并为其赋值索引值。

  • 步骤 7 − 现在,通过将字符和索引作为参数传递给函数,调用 getChar() 函数。

  • 步骤 8 − 将函数获得的结果存储在字符串格式的变量中。

  • 步骤 9 − 使用 fmt.Println() 函数在屏幕上打印此值。

示例

在本示例中,我们将使用用户自定义的外部函数从字符串中获取字符。

package main
import "fmt"

// function to get characters from strings using index
func getChar(str string, index int) rune {
	return []rune(str)[index]
}
func main() {
   // initializing a string
   var str string = "Prevention is better than cure"
   fmt.Println("The given string is:", str)
   var index int = 24
   var result string = string(getChar(str, index))
   fmt.Println("The character at index", index, "is:", result)
}

输出

The given string is: Prevention is better than cure
The character at index 24 is: n

方法 2:使用 Split() 函数

我们将使用内置函数获取字符串中存在的字符数组,然后使用索引获取该索引处存在的字符值。

语法

func Split(str, sep string) []string

Split() 函数用于通过提供的分隔符分割字符串。此函数位于 strings 包中,它接收要分割的字符串以及分隔符作为参数。然后,该函数返回最终的字符串数组作为结果。

func Index(s, substr string) int

index() 函数位于 strings 包中,用于获取给定子字符串的第一次出现的索引。该函数接收两个值作为参数。一个是字符串,另一个是要检测其出现的子字符串。然后,该函数以整数格式返回该子字符串的第一次出现位置。

算法

  • 步骤 1 − 首先,我们需要导入 fmt 和 strings 包。

  • 步骤 2 − 然后,开始 main() 函数。在 main() 函数内部,初始化一个字符串类型的变量并为其赋值。

  • 步骤 3 − 此外,在屏幕上打印字符串,并分配一个 int 类型的变量并存储要获取字符的整数数值。

  • 步骤 4 − 现在,使用 strings 包中的 split() 函数获取给定字符串的字符数组。

  • 步骤 5 − 现在,使用上面初始化的索引从字符数组中获取该值处的字符,并将该字符存储在单独的变量中。

  • 步骤 6 − 我们现在已经获得了我们想要获取的字符。使用 fmt.Println() 函数在屏幕上打印该字符。

示例 1

在本示例中,我们将使用 strings 包中的 split() 函数将字符串转换为字符。

package main
import (
	"fmt"
	"strings"
)
func main() {
   // initializing a string
   var str string = "Prevention is better than cure"
   fmt.Println("The given string is:", str)
   var index int = 7
   chars := strings.Split(str, "")
   var result string = chars[index]
   fmt.Println("The character at index", index, "is:", result)
}

输出

The given string is: Prevention is better than cure
The character at index 7 is: i

示例 2

package main
import (
	"fmt"
	"strings"
)
func main() {
   // initializing a string
   var str string = "Prevention is better than cure"
   fmt.Println("The given string is:", str)
   var index int = 17

   var result string = string(str[strings.Index(str, string(str[index]))])
   fmt.Println("The character at index", index, "is:", result)
}

输出

The given string is: Prevention is better than cure
The character at index 17 is: t

结论

我们已经成功编译并执行了一个 Go 语言程序,该程序使用索引从字符串中获取字符,并附带示例。这里我们编译了三个示例,第一个示例使用外部函数来实现结果,而第二个和第三个示例使用 Go 语言中存在的库函数来实现相同的功能。

更新于: 2023年2月13日

4K+ 次浏览

开启您的 职业生涯

通过完成课程获得认证

立即开始
广告

© . All rights reserved.