One place for hosting & domains

      Strings

      An Introduction to the Strings Package in Go


      Introduction

      Go’s string package has several functions available to work with the string data type. These functions let us easily modify and manipulate strings. We can think of functions as being actions that we perform on elements of our code. Built-in functions are those that are defined in the Go programming language and are readily available for us to use.

      In this tutorial, we’ll review several different functions that we can use to work with strings in Go.

      Making Strings Uppercase and Lowercase

      The functions strings.ToUpper and strings.ToLower will return a string with all the letters of an original string converted to uppercase or lowercase letters. Because strings are immutable data types, the returned string will be a new string. Any characters in the string that are not letters will not be changed.

      Let’s convert the string "Sammy Shark" to be all uppercase:

      ss := "Sammy Shark"
      fmt.Println(strings.ToUpper(ss))
      

      Output

      SAMMY SHARK

      Now, let’s convert the string to be all lowercase:

      fmt.Println(strings.ToLower(ss))
      

      Output

      sammy shark

      Since you are using the strings package, you first need to import it into your program. To convert the string to uppercase and lowercase the entire program would be as follows:

      package main
      
      import (
          "fmt"
          "strings"
      )
      
      func main() {
          ss := "Sammy Shark"
          fmt.Println(strings.ToUpper(ss))
          fmt.Println(strings.ToLower(ss))
      }
      

      The strings.ToUpper and strings.ToLower functions make it easier to evaluate and compare strings by making case consistent throughout. For example, if a user writes their name all lowercase, we can still determine whether their name is in our database by checking it against an all uppercase version.

      String Search Functions

      The strings package has a number of functions that help determine if a string contains a specific sequence of characters.

      Function Use
      strings.HasPrefix Searches the string from the beginning
      strings.HasSuffix Searches the string from the end
      strings.Contains Searches anywhere in the string
      strings.Count Counts how many times the string appears

      The strings.HasPrefix and strings.HasSuffix allow you to check to see if a string starts or ends with a specific set of characters.

      Let’s check to see if the string Sammy Shark starts with Sammy and ends with Shark.

      ss := "Sammy Shark"
      fmt.Println(strings.HasPrefix(ss, "Sammy"))
      fmt.Println(strings.HasSuffix(ss, "Shark"))
      

      Output

      true true

      Let’s check to see if the string Sammy Shark contains the sequence Sh:

      fmt.Println(strings.Contains(ss, "Sh"))
      

      Output

      true

      Finally, let’s see how many times the letter S appears in the phrase Sammy Shark:

      fmt.Println(strings.Count(ss, "S"))
      

      Output

      2

      Note: All strings in Go are case sensitive. This means that Sammy is not the same as sammy.

      Using a lowercase s to get a count from Sammy Shark is not the same as using uppercase S:

      fmt.Println(strings.Count(ss, "s"))
      

      Output

      0

      Because S is different than s, the count returned will be 0.

      String functions are useful when you want to compare or search strings in your program.

      Determining String Length

      The built-in function len() returns the number of characters in a string. This function is useful for when you need to enforce minimum or maximum password lengths, or to truncate larger strings to be within certain limits for use as abbreviations.

      To demonstrate this function, we’ll find the length of a sentence-long string:

      openSource := "Sammy contributes to open source."
      fmt.Println(len(openSource))
      

      Output

      33

      We set the variable openSource equal to the string "Sammy contributes to open source." and then passed that variable to the len() function with len(openSource). Finally we passed the function into the fmt.Println() function so that we could see the program’s output on the screen..

      Keep in mind that the len() function will count any character bound by double quotation marks—including letters, numbers, whitespace characters, and symbols.

      Functions for String Manipulation

      The strings.Join, strings.Split, and strings.ReplaceAll functions are a few additional ways to manipulate strings in Go.

      The strings.Join function is useful for combining a slice of strings into a new single string.

      Let’s create a comma-separated string from a slice of strings:

      fmt.Println(strings.Join([]string{"sharks", "crustaceans", "plankton"}, ","))
      

      Output

      sharks,crustaceans,plankton

      If we want to add a comma and a space between string values in our new string, we can simply rewrite our expression with a whitespace after the comma: strings.Join([]string{"sharks", "crustaceans", "plankton"}, ", ").

      Just as we can join strings together, we can also split strings up. To do this, we use the strings.Split function and split on the spaces:

      balloon := "Sammy has a balloon."
      s := strings.Split(balloon, " ")
      fmt.Println(s)
      

      Output

      [Sammy has a balloon]

      The output is a slice of strings. Since strings.Println was used, it is hard to tell what the output is by looking at it. To see that it is indeed a slice of strings, use the fmt.Printf function with the %q verb to quote the strings:

      fmt.Printf("%q", s)
      

      Output

      ["Sammy" "has" "a" "balloon."]

      Another useful function in addition to strings.Split is strings.Fields. The difference is that strings.Fields will ignore all whitespace, and will only split out the actual fields in a string:

      data := "  username password     email  date"
      fields := strings.Fields(data)
      fmt.Printf("%q", fields)
      

      Output

      ["username" "password" "email" "date"]

      The strings.ReplaceAll function can take an original string and return an updated string with some replacement.

      Let’s say that the balloon that Sammy had is lost. Since Sammy no longer has this balloon, we will change the substring "has" from the original string balloon to "had" in a new string:

      fmt.Println(strings.ReplaceAll(balloon, "has", "had"))
      

      Within the parentheses, first is balloon the variable that stores the original string; the second substring "has" is what we want to be replaced, and the third substring "had" is what we are replacing that second substring with. Our output will look like this:

      Output

      Sammy had a balloon.

      Using the string function strings.Join, strings.Split, and strings.ReplaceAll will provide you with greater control to manipulate strings in Go.

      Conclusion

      This tutorial went through some of the common string package functions for the string data type that you can use to work with and manipulate strings in your Go programs.

      You can learn more about other data types in Understanding Data Types and read more about strings in An Introduction to Working with Strings.



      Source link

      How To Format Strings in Go


      As strings are often made up of written text, there are many instances when we may want to have greater control over how strings look to make them more readable for humans through punctuation, line breaks, and indentation.

      In this tutorial, we’ll go over some of the ways we can work with Go strings to make sure that all output text is formatted correctly.

      String Literals

      Let’s first differentiate between a string literal and a string value. A string literal is what we see in the source code of a computer program, including the quotation marks. A string value is what we see when we call the fmt.Println function and run the program.

      In the “Hello, World!” program, the string literal is "Hello, World!" while the string value is Hello, World! without the quotation marks. The string value is what we see as the output in a terminal window when we run a Go program.

      But some string values may need to include quotation marks, like when we are quoting a source. Because string literals and string values are not equivalent, it is often necessary to add additional formatting to string literals to ensure that string values are displayed the way in which we intend.

      Quotes

      Because we can use back quotes (`) or double quotes (") within Go, it is simple to embed quotes within a string by using double quotes within a string enclosed by back quotes:

      `Sammy says, "Hello!"`
      

      Or, to use a back quote, you can enclose the string in double quotes:

      "Sammy likes the `fmt` package for formatting strings.."
      

      In the way we combine back quotes and double quotes, we can control the display of quotation marks and back quotes within our strings.

      It’s important to remember that using back quotes in Go creates a raw string literal, and using double quotes creates an interpreted string literal. To learn more about the difference, read the An Introduction to Working with Strings in Go tutorial.

      Escape Characters

      Another way to format strings is to use an escape character. Escape characters are used to tell the code that the following character has a special meaning. Escape characters all start with the backslash key () combined with another character within a string to format the given string a certain way.

      Here is a list of several of the common escape characters:

      Escape Character How it formats
      \ Backslash
      Double Quote
      n Line Break
      t Tab (horizontal indentation)

      Let’s use an escape character to add the quotation marks to the example on quotation marks above, but this time we’ll use double quotes to denote the string:

      fmt.Println("Sammy says, "Hello!"")
      

      Output

      Sammy says, "Hello!"

      By using the escape character " we are able to use double quotes to enclose a string that includes text quoted between double quotes.

      We can use the n escape character to break lines without hitting the enter or return key:

      fmt.Println("This stringnspans multiplenlines.")
      

      Output

      This string spans multiple lines.

      We can combine escape characters, too. Let’s print a multi-line string and include tab spacing for an itemized list, for example:

      fmt.Println("1.tSharkn2.tShrimpn10.tSquid")
      

      Output

      1. Shark 2. Shrimp 10. Squid

      The horizontal indentation provided with the t escape character ensures alignment within the second column in the preceding example, making the output extremely readable for humans.

      Escape characters are used to add additional formatting to strings that may be difficult or impossible to achieve. Without escape characters, you would not be able to construct the string Sammy says, "I like to use the `fmt` package".

      Multiple Lines

      Printing strings on multiple lines can make text more readable to humans. With multiple lines, strings can be grouped into clean and orderly text, formatted as a letter, or used to maintain the linebreaks of a poem or song lyrics.

      To create strings that span multiple lines, back quotes are used to enclose the string. Keep in mind that while this will preserve the line returns, it is also creating a raw string literal.

      `
      This string is on 
      multiple lines
      within three single 
      quotes on either side.
      `
      

      You will notice if you print this that there is a leading and trailing return:

      Output

      This string is on multiple lines within three single quotes on either side.

      To avoid this, you need to put the first line immediately following the back quote and end the last with the back quote.

      `This string is on 
      multiple lines
      within three single 
      quotes on either side.`
      

      If you need to create an interpreted string literal, this can be done with double quotes and the + operator, but you will need to insert your own line breaks.

      "This string is onn" +
      "multiple linesn" +
      "within three singlen" +
      "quotes on either side."
      

      While back quotes can make it easier to print and read lengthy text, if you need an interpreted string literal, you will need to use double quotes.

      Raw String Literals

      What if we don’t want special formatting within our strings? For example, we may need to compare or evaluate strings of computer code that use the backslash on purpose, so we won’t want Go to use it as an escape character.

      A raw string literal tells Go to ignore all formatting within a string, including escape characters.

      We create a raw string by using back quotes around the string:

      fmt.Println(`Sammy says,"The balloon's color is red."`)
      

      Output

      Sammy says,"The balloon's color is red."

      By constructing a raw string by using back quotes around a given string, we can retain backslashes and other characters that are used as escape characters.

      Conclusion

      This tutorial went over several ways to format text in Go through working with strings. By using techniques such as escape characters or raw strings, we are able to ensure that the strings of our program are rendered correctly on-screen so that the end user is able to easily read all of the output text.



      Source link

      An Introduction to Working with Strings in Go


      A string is a sequence of one or more characters (letters, numbers, symbols) that can be either a constant or a variable. Made up of Unicode, strings are immutable sequences, meaning they are unchanging.

      Because text is such a common form of data that we use in everyday life, the string data type is a very important building block of programming.

      This Go tutorial will go over how to create and print strings, how to concatenate and replicate strings, and how to store strings in variables.

      String Literals

      In Go, strings exist within either back quotes ` (sometimes referred to as back ticks) or double quotes ". Depending on which quotes you use, the string will have different characteristics.

      Using back quotes, as in `bar`, will create a raw string literal. In a raw string literal, any character may appear between quotes, with the exception of back quotes. Here’s an example of a raw string literal:

      `Say "hello" to Go!`
      

      Backslashes have no special meaning inside of raw string literals. For instance, n will appear as the actual characters, backslash and letter n. Unlike interpreted string literals, in which n would insert an actual new line.

      Raw string literals may also be used to create multi-line strings:

      `Go is expressive, concise, clean, and efficient.
      Its concurrency mechanisms make it easy to write programs
      that get the most out of multi-core and networked machines,
      while its novel type system enables flexible and modular
      program construction. Go compiles quickly to machine code
      yet has the convenience of garbage collection and the power
      of run-time reflection. It's a fast, statically typed,
      compiled language that feels like a dynamically typed,
      interpreted language.`
      

      Interpreted string literals are character sequences between double quotes, as in "bar". Within the quotes, any character may appear with the exception of newline and unescaped double quotes.

      "Say "hello" to Go!"
      

      You will almost always use interpreted string literals because they allow for escape characters within them.

      Now that you understand how strings are formatted in Go, let’s take a look at how you can print strings in programs.

      Printing Strings

      You can print out strings by using the fmt package from the system library and calling the Println() function:

      fmt.Println("Let's print out this string.")
      

      Output

      Let's print out this string.

      You have to import system packages when you use them, so a simple program to print out a string would look like this:

      package main
      
      import "fmt"
      
      func main() {
          fmt.Println("Let's print out this string.")
      }
      

      String Concatenation

      Concatenation means joining strings together, end-to-end, to create a new string. You can concatenate strings with the + operator. Keep in mind that when you work with numbers, + will be an operator for addition, but when used with strings it is a joining operator.

      Let’s combine the string literals "Sammy" and "Shark" together with concatenation through a fmt.Println() statement:

      fmt.Println("Sammy" + "Shark")
      

      Output

      SammyShark

      If you would like a whitespace between the two strings, you can simply include the whitespace within a string. In this example, add the whitespace within the quotes after Sammy:

      fmt.Println("Sammy " + "Shark")
      

      Output

      Sammy Shark

      The + operator can not be used between two different data types. As an example, you can’t concatenate strings and integers together. If you were to try to write the following:

      fmt.Println("Sammy" + 27)
      

      You will receive the following errors:

      Output

      cannot convert "Sammy" (type untyped string) to type int invalid operation: "Sammy" + 27 (mismatched types string and int)

      If you wanted to create the string "Sammy27", you could do so by putting the number 27 in quotes ("27") so that it is no longer an integer but is instead a string. Converting numbers to strings for concatenation can be useful when dealing with zip codes or phone numbers. For example, you wouldn’t want to perform addition between a country code and an area code, but you do want them to stay together.

      When you combine two or more strings through concatenation, you are creating a new string that you can use throughout your program.

      Storing Strings in Variables

      Variables are symbols that you can use to store data in a program. You can think of them as an empty box that you fill with some data or value. Strings are data, so you can use them to fill up a variable. Declaring strings as variables can make it easier to work with strings throughout your Go programs.

      To store a string inside a variable, simply assign a variable to a string. In this case, declare s as your variable:

      s := "Sammy likes declaring strings."
      

      Note: If you’re familiar with other programming languages, you may have written the variable as sammy. Go, however, favors shorter variable names. Choosing s for the variable name in this case would be considered more appropriate for the style in which Go is written.

      Now that you have the variable s set to that particular string, you can print the variable like so:

      fmt.Println(s)
      

      You will then receive the following output:

      Output

      Sammy likes declaring strings.

      By using variables to stand in for strings, you do not have to retype a string each time you want to use it, making it more simple for you to work with and manipulate strings within your programs.

      Conclusion

      This tutorial went over the basics of working with the string data type in the Go programming language. Creating and printing strings, concatenating and replicating strings, and storing strings in variables will provide you with the fundamentals to use strings in your Go programs.



      Source link