必須認真思考這個標題嗎? ……現在我們已經解決了這個問題,讓我們來寫一些該死的程式碼:)
幫浦煞車?尖叫……讓我們對今天要嘗試建立的內容做一些介紹。如果標題不明顯,我們將建立一個 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
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

DVWA
Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

mPDF
mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

Atom編輯器mac版下載
最受歡迎的的開源編輯器

MantisBT
Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

ZendStudio 13.5.1 Mac
強大的PHP整合開發環境