Golang 在字符串中计算数字位数
使用引号创建的字符序列是Golang中的字符串。字符串在此处是不可变的,这意味着一旦创建就不能修改。我们将使用字符串来查找其中包含的数字位数。在本文中,我们将编写一个Go语言程序来计算字符串中的数字位数。
演示
本演示说明了“helloalexa234567playthesong”是一个输入字符串,其中包含六个数字位数,程序的作用是统计提供的字符串中所有可用的数字位数。
- 输入字符串 − helloalexa234567playthesong
-
数字位数 − 6
语法
unicode.IsDigit()
此函数属于unicode包。它用于检查Unicode代码点是否代表数字。如果代表数字,则返回true,否则返回false。
regexp.MustCompile()
这个函数是正则表达式包中返回编译后的正则表达式表达式的一部分。
regex.FindAllString()
此函数用于在字符串中查找表达式的匹配模式。它接受两个参数:字符串和-1,表示匹配的数量没有限制。
func range(variable)
range(范围)函数用于迭代任何数据类型。要使用它,我们首先需要写上range关键字,然后跟上要迭代的数据类型,作为结果,循环将迭代到变量的最后一个元素。
funclen(v Type) int
len()函数用于获取任何参数的长度。它接受一个参数作为数据类型变量,我们希望找到其长度,并返回整数值,该值是变量的长度。
步骤
- 步骤1 − 此程序导入两个包fmt和Unicode,前者用于输入和输出的格式化,后者用于查找数字
-
步骤2 − 创建一个主函数,在该函数中创建一个字符串,并将其分配给mystr
-
步骤3 − 使用fmt包的Println函数在控制台上打印字符串
-
步骤4 − 在此步骤中,将变量count赋值为零,并在上述创建的字符串上运行循环,并使用Unicode包检查字符串中是否存在数值数字
-
步骤5 − 如果数字数字存在于字符串中,则增加count变量,并在循环终止之前不断增加
-
步骤6 − 最后,数字数字的计数将被获得并存储在count变量中
-
步骤7 − 使用fmt包的Println函数将count变量打印在控制台上,其中ln表示换行
示例1
在这个示例中,我们将创建一个主函数,在该函数中使用unicode包计算数字数字,每当找到一个数字数字时,count将会增加使用IsDigit函数。
package main
import (
"fmt"
"unicode"
)
func main() {
mystr := "helloalexa666424playthesong46"
fmt.Println("The string in which numerical digit is to be counted is:", mystr)
count := 0
for _, char := range mystr {
if unicode.IsDigit(char) {
count++
}
}
fmt.Println("Number of numerical digits in the string are:", count)
}
输出
The string in which numerical digit is to be counted is: helloalexa666424playthesong46
Number of numerical digits in the string are: 8
示例2
在这个示例中,将使用if条件语句来检查字符串中的字符是否为任何数字。如果条件满足,则计数变量将增加。
package main
import (
"fmt"
)
func main() {
mystr := "helloalexa234567playthesong"
fmt.Println("The string created here is:", mystr)
count := 0
for _, char := range mystr {
if char >= '0' && char <= '9' {
count++
}
}
fmt.Println("Number of numerical digits:", count)
}
输出
The string created here is: helloalexa234567playthesong
Number of numerical digits: 6
示例3
在这个示例中,regexp包将被用来在字符串中找到数字。最后,我们将计算结果切片的长度,从而得到字符串中的总数字个数。
package main
import (
"fmt"
"regexp"
)
func main() {
mystr := "helloalexa234568playthesong"
fmt.Println("The string from which numerical digits is to be counted:", mystr)
regex := regexp.MustCompile(`\d`)
count := len(regex.FindAllString (mystr, -1))
fmt.Println("Number of numerical digits in the string are:", count)
}
输出
The string from which numerical digits is to be counted: helloalexa234568playthesong
Number of numerical digits in the string are: 6
结论
我们编写并执行了三个示例程序,用于计算字符串中数字位数。在第一个示例中, 我们使用了Unicode包中的IsDigit方法,在第二个示例中,我们使用了if条件语句,在第三个示例中,我们使用了regexp包来执行该程序。