String in golang


Strings are sequence of characters with definite length and can be created by enclosing in double quotes "Hello Go" and back ticks `Hello Go`.
  1.  A string is a sequence of characters.
  2. Strings are the collection of individual bytes, where each character occupy single byte.
  3. Characters out of the ASCII characters (can say characters from other languages) occupy more than one byte.
  4. A string can be created by enclosing in double quotes "Hello Go" or backticks `Hello Go`.
  5. The difference between double quotes and backticks is that double quotes allow escape sequences like \n (newline) and \t (tab) and parses them but backticks don't.

Example-1:

package main
import "fmt"
func main( ) {
        fmt.Println(len("Hello Go"))
        fmt.Println("Hello Go"[1])
        fmt.Println("Hello"+" "+"Go")
}

Output: 

  1. 8
  2. 101
  3. Hello Go 


 Output Explained:

  1. fmt.Println(len("Hello Go")) returns the length of the string "Hello Go" which is 8 characters long including space.
  2. fmt.Println("Hello Go"[1]) return 101 because the string can be treated as an array of characters and if "Hello Go" is an array of characters then "Hello Go"[1] returns second characters of the array as array index starts with 0, which returns 'e'. But in go lang string is a sequence of bytes so character 'e' byte value gets printed that is 101.
    1. For reference here is the common characters ASCII range as below.
  3. fmt.Println("Hello"+" "+"Go") return "Hello Go", because when '+' operator is used with strings then it performs concatenate means it merges string. so here the output will be "Hello" merged with " "(space) and then merged with "Go".

Comments

Sir please explain the output of second line. fmt.Println("Hello Go"[1])
And why there are no semicolons??
IdiotsDiary said…
In Go string is treated as sequence of bytes or array of bytes, so "Hello Go"[1] return bytes value (ASCII value) of 'e' that is 101.

Popular posts from this blog

Inline V/S Block Level Element

Arrays in C Language

Data Types in Go language

Printing in C programming

Variable Naming & Scope of Variable

Escape Sequence | Formatted Printing | Interview Questions

Floating point Data types in Go lang

Overview of Go lang

Literals in Java