必须认真思考这个标题吗?...现在我们已经解决了这个问题,让我们编写一些该死的代码:)
泵刹车?尖叫……让我们对今天要尝试构建的内容做一些介绍。如果标题不明显,我们将构建一个 CLI 应用程序来计算您在 golang 中的打字速度 - 尽管您可以使用您选择的任何编程语言遵循相同的技术来构建相同的应用程序。
现在,我们来编码吧?
package main import ( "bufio" "fmt" "log" "math/rand" "os" "strings" "time" ) var sentences = []string{ "There are 60 minutes in an hour, 24 hours in a day and 7 days in a week", "Nelson Mandela is one of the most renowned freedom fighters Africa has ever produced", "Nigeria is the most populous black nation in the world", "Peter Jackson's Lord of the rings is the greatest film of all time", }
在 main.go 文件中,我们导入编写逻辑所需的包。我们还创建了一个句子片段。欢迎添加更多。
// A generic helper function that randomly selects an item from a slice func Choice[T any](ts []T) T { return ts[rand.Intn(len(ts))] } // Prompts and collects user input from the terminal func Input(prompt string) (string, error) { fmt.Print(prompt) r := bufio.NewReader(os.Stdin) line, err := r.ReadString('\n') if err != nil { return "", err } return strings.Trim(line, "\n\r\t"), nil } // Compares two strings and keeps track of the characters // that match and those that don't func CompareChars(target, source string) (int, int) { var valid, invalid int // typed some of the words // resize target to length of source if len(target) > len(source) { diff := len(target) - len(source) invalid += diff target = target[:len(source)] } // typed more words than required // resize source to length of target if len(target) <p>然后我们继续创建几个函数,这些函数在我们编写应用程序逻辑时会派上用场。<br> </p> <pre class="brush:php;toolbar:false">func main() { fmt.Println("Welcome to Go-Speed") fmt.Println("-------------------") for { fmt.Printf("\nWould you like to continue? (y/N)\n\n") choice, err := Input(">> ") if err != nil { log.Fatalf("could not read value: %v", err) } if choice == "y" { fmt.Println("Starting Game...") timer := time.NewTimer(time.Second) fmt.Print("\nBEGIN TYPING NOW!!!\n\n") _ = > ") if err != nil { log.Fatalf("could not read value: %v", err) } elasped := timeElapsed(start, time.Now()) valid, invalid := CompareChars(sentence, response) fmt.Print("\nResult!\n") fmt.Println("-------") fmt.Printf("Correct Characters: %d\nIncorrect Characters: %d\n", valid, invalid) fmt.Printf("Accuracy: %d%%\n", accuracy(valid, len(sentence))) fmt.Printf("Precision: %d%%\n", precision(valid, invalid)) fmt.Printf("Speed: %.1fwpm\n", Speed(len(sentence), elasped)) fmt.Printf("Time Elasped: %.2fsec\n", elasped) } if choice == "N" { fmt.Println("Quiting Game...") break } if choice != "N" && choice != "y" { fmt.Println("Invalid Option") } } }
在我们的主函数中,我们向终端写入一条欢迎消息,并创建一个无限循环来运行我们的程序。然后,我们将确认消息打印到标准输出(终端),并提供退出程序的选项。如果您选择继续,则会从先前编写的句子片段中选择一个句子,并在记录开始时间后立即显示在终端中。我们收集用户输入并计算时间、速度、精度和准确度,然后将结果显示回终端。无限循环重置,应用程序再次运行,直到您选择退出该程序。
瞧!!!我们刚刚用 golang 编写了第一个程序。
以上是使用 Golang 编写打字速度测试 CLI 应用程序的详细内容。更多信息请关注PHP中文网其他相关文章!

掌握Go语言中的strings包可以提高文本处理能力和开发效率。1)使用Contains函数检查子字符串,2)用Index函数查找子字符串位置,3)Join函数高效拼接字符串切片,4)Replace函数替换子字符串。注意避免常见错误,如未检查空字符串和大字符串操作性能问题。

你应该关心Go语言中的strings包,因为它能简化字符串操作,使代码更清晰高效。1)使用strings.Join高效拼接字符串;2)用strings.Fields按空白符分割字符串;3)通过strings.Index和strings.LastIndex查找子串位置;4)用strings.ReplaceAll进行字符串替换;5)利用strings.Builder进行高效字符串拼接;6)始终验证输入以避免意外结果。

thestringspackageingoisesential forefficientstringManipulation.1)itoffersSimpleyetpoperfulfunctionsFortaskSlikeCheckingSslingSubstringsStringStringsStringsandStringsN.2)ithandhishiCodeDewell,withFunctionsLikestrings.fieldsfieldsfieldsfordsforeflikester.fieldsfordsforwhitespace-fieldsforwhitespace-separatedvalues.3)3)

WhendecidingbetweenGo'sbytespackageandstringspackage,usebytes.Bufferforbinarydataandstrings.Builderforstringoperations.1)Usebytes.Bufferforworkingwithbyteslices,binarydata,appendingdifferentdatatypes,andwritingtoio.Writer.2)Usestrings.Builderforstrin

Go的strings包提供了多种字符串操作功能。1)使用strings.Contains检查子字符串。2)用strings.Split将字符串分割成子字符串切片。3)通过strings.Join合并字符串。4)用strings.TrimSpace或strings.Trim去除字符串首尾的空白或指定字符。5)用strings.ReplaceAll替换所有指定子字符串。6)使用strings.HasPrefix或strings.HasSuffix检查字符串的前缀或后缀。

使用Go语言的strings包可以提升代码质量。1)使用strings.Join()优雅地连接字符串数组,避免性能开销。2)结合strings.Split()和strings.Contains()处理文本,注意大小写敏感问题。3)避免滥用strings.Replace(),考虑使用正则表达式进行大量替换。4)使用strings.Builder提高频繁拼接字符串的性能。

Go的bytes包提供了多种实用的函数来处理字节切片。1.bytes.Contains用于检查字节切片是否包含特定序列。2.bytes.Split用于将字节切片分割成smallerpieces。3.bytes.Join用于将多个字节切片连接成一个。4.bytes.TrimSpace用于去除字节切片的前后空白。5.bytes.Equal用于比较两个字节切片是否相等。6.bytes.Index用于查找子切片在largerslice中的起始索引。

theEncoding/binarypackageingoisesenebecapeitProvidesAstandArdArdArdArdArdArdArdArdAndWriteBinaryData,确保Cross-cross-platformCompatibilitiational and handhandlingdifferentendenness.itoffersfunctionslikeread,写下,写,dearte,readuvarint,andwriteuvarint,andWriteuvarIntforPreciseControloverBinary


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

禅工作室 13.0.1
功能强大的PHP集成开发环境

VSCode Windows 64位 下载
微软推出的免费、功能强大的一款IDE编辑器

PhpStorm Mac 版本
最新(2018.2.1 )专业的PHP集成开发工具

适用于 Eclipse 的 SAP NetWeaver 服务器适配器
将Eclipse与SAP NetWeaver应用服务器集成。

安全考试浏览器
Safe Exam Browser是一个安全的浏览器环境,用于安全地进行在线考试。该软件将任何计算机变成一个安全的工作站。它控制对任何实用工具的访问,并防止学生使用未经授权的资源。