Created
          August 12, 2014 10:19 
        
      - 
      
- 
        Save prakhar1989/e393594ba379011c57df to your computer and use it in GitHub Desktop. 
    Understanding Strings
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | package main | |
| import "fmt" | |
| func main() { | |
| //const sample = "\xbd\xb2\x3d\xbc\x20\xe2\x8c\x98" | |
| //const sample = "Hello" | |
| // sample as a slice of bytes | |
| sample := []byte{'H', 'e', 'l', 'l', 'o'} | |
| for i := 0; i < len(sample); i++ { | |
| fmt.Printf("char: %c, int: %d, hex: %x, utf-8: u00%x\n", | |
| sample[i], sample[i], sample[i], sample[i]) | |
| } | |
| // another way of printing the above | |
| fmt.Printf("Bytes: % x\n", sample) | |
| // escape non-printable characters | |
| fmt.Printf("Printable characters(only): %q\n", sample) | |
| // escape non-printable and show only ASCII | |
| fmt.Printf("ASCII only: %+q\n", sample) | |
| } | 
package main
import "fmt"
func main() {
    // stored as raw string (arabic character) ... no escape sequences
    const placeOfInterest = `ل` // try making this an english char to see diff
    funnyPrintln(placeOfInterest)
    funnyPrintln("a")
}
func funnyPrintln(c string) {
    fmt.Printf("Plain string: %s\n", c)
    fmt.Printf("Unicode (quoted) string: %+q\n", c)
    fmt.Printf("Hex Bytes:")
    for i := 0; i < len(c); i++ {
        fmt.Printf("% x", c[i])
    }
    fmt.Printf("\n------\n")
}For loop and ranges over strings
package main
import "fmt"
func main() {
    diffForRange("prakhar") // english
    diffForRange("日本語")   // chinese
    diffForRange("المزيد")  // arabic
}
func diffForRange(s string) {
    for i := 0; i < len(s); i++ {
        fmt.Printf("%c, ", s[i])
    }
    fmt.Println()
    // to get each rune, always use range rather than for   
    for index, runeValue := range s {
        fmt.Printf("%#U starts at byte position %d\n", runeValue, index)
    }
}
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment
  
            
Source: http://blog.golang.org/strings