String Literal Examples (Repeat Method)
This page was last reviewed on Nov 15, 2023.
Dot Net Perls
String literals. Often programs need to have string data specified within the programs themselves. This data is usually in the form of string literals.
With the best syntax, we can make our programs easier to read. Raw string literals in Golang use tick characters. Regular expressions often benefit from raw literals.
Syntax example. Go supports 2 syntaxes for string literals. With regular quotes, special sequences like newlines are interpreted as actual newlines.
And With the backtick character, escape sequences are ignored. The chars are treated as normal values.
package main import "fmt" func main() { // The newline sequence is treated as a special value. value1 := "cat\ndog" fmt.Println(value1) // The newline sequence is treated as two raw chars. value2 := `cat\ndog` fmt.Println(value2) }
cat dog cat\ndog
Repeat. With the Repeat func we can repeat a string. The first argument is the string we want to repeat, and the second is the count of repetitions.
Tip For creating repeating text, using Repeat() with a string literal is a good solution.
package main import ( "fmt" "strings" ) func main() { // Create a new string based on a repetition. result := strings.Repeat("abc...", 3) fmt.Println(result) }
A summary. String literal syntax can improve a program's readability. With Repeat() and the best literal syntax form, programs are easier to read—and this will tend to lead to fewer bugs.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Nov 15, 2023 (edit).
© 2007-2024 Sam Allen.