Golang 检查给定的字符串是否为Pangram
在本文中,我们将了解使用不同的Golang示例来检查给定的字符串是否为Pangram。Pangram是指每个字母至少出现一次的语句。Pangram是指包含了英文字母的字符串,不论大小写。
语法
strings.ToLower(str)
使用Go语言中的字符串,您可以将字符串的大小写转换为小写。字符串包下的ToLower()函数。
func make ([] type, size, capacity)
在Go语言中,make函数用于创建数组/映射,它接受要创建的变量类型、大小和容量作为参数
方法1:使用映射
在这个方法中,我们将使用映射来检查给定的字符串是否为Pangram。除此之外,我们还将使用ToLower和Make等内部函数。
步骤
- 步骤1 - 在程序中创建一个main包,并声明fmt(格式化包)和strings(字符串包)。其中,main用于生成可执行的示例,fmt用于格式化输入和输出。
-
步骤2 - 创建一个isPangram函数,并在函数内部使用ToLower()方法将给定字符串的大小写转换为小写。
-
步骤3 - 使用make函数创建一个映射,用于存储字符串中每个字母的频率。
-
步骤4 - 逐个遍历字符串的字符。
-
步骤5 - 如果字符是字母,则增加映射中该字符的频率,并对字母表中的每个字母(从”a”到”z”)重复此过程。
-
步骤6 - 验证映射中当前字母的频率是否大于零,如果任何字母的频率为零,则返回false。
-
步骤7 - 如果所有字母的频率之和大于零,则返回true。
-
步骤8 - 通过计算每个字母的频率并确定它是否大于零,该算法确定字符串中是否存在每个字母。如果每个字母都具有正频率,则字符串被视为Pangram。
示例
在此示例中,我们将看到如何使用映射来检查给定字符串是否为Pangram。
package main
import (
"fmt"
"strings"
)
func isPangram(str string) bool {
// make all characters lowercase
str = strings.ToLower(str)
// create a map to store the frequency of each character
m := make(map[rune]int)
// iterate over each character in the string
for _, c := range str {
// if the character is a letter, increase its frequency in the map
if c >= 'a' && c <= 'z' {
m[c]++
}
}
// check if the frequency of each letter is greater than zero
for i := 'a'; i <= 'z'; i++ {
if m[i] == 0 {
return false
}
}
return true
}
func main() {
str := "I am a frontend developer"
fmt.Println("The pangram is checked as:")
if isPangram(str) {
fmt.Println(str, "is a pangram")
} else {
fmt.Println(str, "is not a pangram")
}
}
输出
The pangram is checked as:
I am a frontend developer is not a pangram
方法2:使用Set
在这种方法中,我们将使用set来检查给定的字符串是否是全字母句。
步骤
- 步骤1 - 在程序的main函数中创建一个包main,声明fmt(格式包)和strings包,其中main产生可执行的Example:s,fmt用于格式化输入和输出。
-
步骤2 - 创建一个isPangram函数,并在该函数内创建一个set来存储字符串的唯一字符。
-
步骤3 - 使用strings.ToLower()将给定字符串的大小写转换为小写。
-
步骤4 - 逐个检查字符串的字符。
-
步骤5 - 如果字符是字母,则将其添加到set中,并验证set是否有26个元素。
-
步骤6 - 如果set中有26个不同的字符,则返回true;如果set中的唯一字符少于26个,则返回false。
-
步骤7 - 通过将唯一字符添加到set中,并确定set的长度是否为26,该算法确定字符串是否包含字母表中的每个字母。如果是的话,返回true;否则,返回false。如果字符串中包含了字母表中的每个字母,则set中将有26个不同的字符。
示例
在这个示例中,我们将使用set来检查给定的字符串是否是全字母句。
package main
import (
"fmt"
"strings"
)
func isPangram(str string) bool {
// create a set to store the unique characters in the string using make function
set_create := make(map[rune]bool)
// make all the character lowercase
str = strings.ToLower(str)
// iterate over each character in the string
for _, c := range str {
// if the character is a letter, add it to the set
if c >= 'a' && c <= 'z' {
set_create[c] = true
}
}
// check if the set contains 26 unique characters
return len(set_create) == 26
}
func main() {
str := "I am a frontend developer"
if isPangram(str) {
fmt.Println(str, "is a pangram")
} else {
fmt.Println(str, "is not a pangram")
}
}
输出
I am a frontend developer is not a pangram
结论
我们通过两个示例执行了检查给定字符串是否为“全字母句”的程序。在第一个示例中,我们使用了map,在第二个示例中,我们使用了set来执行程序。