TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to GO

Golang First Words in String

Use a for-loop and counts spaces to get the first words of a string in a substring.
First words. A string has words. It contains a sentence, a paragraph. Words are separated with spaces. With a special func we can extract the first words in the sentence.
By counting spaces, we can estimate the number of words. This is not perfect. Extra logic to handle hyphens and punctuation might be needed.
Example func. The firstWords func receives to arguments: a string and a count. The count int is the number of words in our result.Strings

For: We use a for-loop to count spaces. We decrement the count by 1 (meaning one less word is remaining to be counted).

For

Return: We return a substring to the current index when the required number of spaces are found. We do not include the trailing space.

Golang program that gets first words package main import "fmt" func firstWords(value string, count int) string { // Loop over all indexes in the string. for i := range value { // If we encounter a space, reduce the count. if value[i] == ' ' { count -= 1 // When no more words required, return a substring. if count == 0 { return value[0:i] } } } // Return the entire string. return value } func main() { value := "there are many reasons" // Test our first words method. result1 := firstWords(value, 2) fmt.Println("[" + result1 + "]") result2 := firstWords(value, 3) fmt.Println(result2) result3 := firstWords(value, 100) fmt.Println(result3) } Output [there are] there are many there are many reasons
Entire string, notes. If you pass a large value to firstWords, like 100, the entire string is returned. The argument 0 may need to be special-cased depending on your requirements.
Substrings are complex. Each language has special syntax for them. In Go we use a slice of a string. We can extract parts of strings, like the first several words, with this syntax.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf