Golang program to print first letter of each word using regex


A string of characters known as a regular expression (regex or regexp) creates a search pattern. Regular expressions are frequently employed to carry out string matching, sometimes known as "find and replace," or pattern matching with strings. Input validation, parsing, and other tasks are also possible with them. Regular expressions use special characters and metacharacters to specify the pattern to be matched, and their syntax differs widely between computer languages. Let’s see different Golang examples to get a clear view of the concept.

Method 1: Using regex.MustCompile() function

In this example, we will see how to print first letter of each word using regex.MustCompile() function.This program creates a regular expression that matches the initial letter of each word using the regexp library. The input string is searched for every instance of the regular expression that matches it using the FindAllString method, and the resulting slice of strings is reported to the console. Let’s go through the Example: and algorithm to get a clear understanding of the concept.

Syntax

regex.MustCompile()

The Go standard library's regexp package contains a function called MustCompile() that converts a regular expression pattern into a regexp. struct with regex. Then, using functions like FindAllString(), FindString(), and ReplaceAllString, this struct may be used to compare against other strings (). A convenience function, MustCompile() panics if the expression cannot be parsed and wraps the Compile() function.

Algorithm

  • Step 1 − Create a package main and declare fmt(format package) and regexp package in the program where main produces executable Example:s and fmt helps in formatting input and output.

  • Step 2 − Create a function main and in that function create a regular expression object that matches the initial letter of each word by using the regexp.MustCompile function.

  • Step 3 − To discover every instance of the regular expression in the input string, use the FindAllString function on the regular expression object.

  • Step 4 − Put the FindAllString function's output in a variable named print_firstletter.

  • Step 5 − To print the resulting slice of strings to the console, use the fmt.Println method.

  • Step 6 − This algorithm prints out all words that match the input string's first letter using regular expressions.

Example

package main
import (
   "fmt"
   "regexp"
)

func main() {
   mystr := "Hello, alexa!" //create a string
   fmt.Println("The inital value of string is:", mystr)
   reg := regexp.MustCompile("\b[a-zA-Z]") //create a regular expression object
   print_firstletter := reg.FindAllString(mystr, -1)
   fmt.Println("The first letter of each word is:")
   fmt.Println(print_firstletter)  //print first letter of each word
}

Output

The inital value of string is: Hello, alexa!
The first letter of each word is:
[]

Method 2: Using strings.Field() function

In this method, we use the fields function, the input string is divided into a word-by-word iteration using a for loop. It uses string indexing to print the first letter of each word inside the loop. Let’s go through the Example: and algorithm to see its execution.

Syntax

strings.Fields()

The Golang function fields() is used to slice a string into many substrings based on whitespace. All of the substrings of the original text that are separated by whitespace characters are included in the slice that this method returns (spaces, tabs, and newlines). This action does not change the original string.

Algorithm

  • Step 1 − Create a package main and declare fmt(format package) and strings package in the program where main produces executable Example:s and fmt helps in formatting input and output.

  • Step 2 − Create a function main and in that function create a string variable that holds the input value named mystr.

  • Step 3 − Use the strings.Fields() to slice the input string into words and to iterate over the words use a for loop.

  • Step 4 − Use string indexing within the loop to retrieve the current word's initial letter.

  • Step 5 − Print the word's first letter using the fmt.Println() function where ln means new line.

  • Step 6 − For each word, follow steps 4-6 once again.

  • Step 7 − This algorithm loops through the words in the input string and prints the initial letter of each word after each iteration. It is more memory-efficient and does not employ regular expressions.

Example

In this example we will learn how to print first letter of each word using strings.Field() function.

package main
import (
   "fmt"
   "strings"
)

func main() {
   mystr := "Hello, alexa!"   //create a string 
   fmt.Println("The string created here is:", mystr)
   words := strings.Fields(mystr) //use the built-in function to separate the string into words
   fmt.Println("The initial character of the mystr is:")
   for _, word := range words {
      fmt.Print(string(word[0])) //print the first letter of each word
   }
}

Output

The string created here is: Hello, alexa!
The initial character of the mystr is:
Ha

Conclusion

We executed the above program of printing the first character of each word using two examples. In the first example we used regex.MustCompile function and in the second example we used strings.Fields() function. Both the programs give similar output.

Updated on: 20-Feb-2023

343 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements