How to delete the first character of a string?

What is the suggested method for removing the first character of a string?

I looked through the documentation for string methods, but I don't see anything that works like javascript String.slice () .

+10
source share
3 answers

Assuming the question uses a “character” to refer to what Go calls a rune , then use utf8.DecodeRuneInString to get the size of the first rune and then chop:

func trimFirstRune(s string) string {
    _, i := utf8.DecodeRuneInString(s)
    return s[i:]
}

playground example

As peterSO demonstrates on the example of a playground associated with his comment, the line range can also be used to determine where the end of the first rune ends:

func trimFirstRune(s string) string {
    for i := range s {
        if i > 0 {
            // The value i is the index in s of the second 
            // rune.  Slice to remove the first rune.
            return s[i:]
        }
    }
    // There are 0 or 1 runes in the string. 
    return ""
}
+10

Go string - Unicode UTF-8. UTF-8 - .

Go

"range" Unicode , 0. UTF-8 rune . UTF-8, 0xFFFD, Unicode, .

,

package main

import "fmt"

func trimLeftChar(s string) string {
    for i := range s {
        if i > 0 {
            return s[i:]
        }
    }
    return s[:0]
}

func main() {
    fmt.Printf("%q\n", "Hello, 世界")
    fmt.Printf("%q\n", trimLeftChar(""))
    fmt.Printf("%q\n", trimLeftChar("H"))
    fmt.Printf("%q\n", trimLeftChar("世"))
    fmt.Printf("%q\n", trimLeftChar("Hello"))
    fmt.Printf("%q\n", trimLeftChar("世界"))
}

: https://play.golang.org/p/t93M8keTQP_I

:

"Hello, 世界"
""
""
""
"ello"
"界"

, ,

package main

import "fmt"

func trimLeftChars(s string, n int) string {
    m := 0
    for i := range s {
        if m >= n {
            return s[i:]
        }
        m++
    }
    return s[:0]
}

func main() {
    fmt.Printf("%q\n", trimLeftChars("", 1))
    fmt.Printf("%q\n", trimLeftChars("H", 1))
    fmt.Printf("%q\n", trimLeftChars("世", 1))
    fmt.Printf("%q\n", trimLeftChars("Hello", 1))
    fmt.Printf("%q\n", trimLeftChars("世界", 1))
    fmt.Println()
    fmt.Printf("%q\n", "Hello, 世界")
    fmt.Printf("%q\n", trimLeftChars("Hello, 世界", 0))
    fmt.Printf("%q\n", trimLeftChars("Hello, 世界", 1))
    fmt.Printf("%q\n", trimLeftChars("Hello, 世界", 7))
    fmt.Printf("%q\n", trimLeftChars("Hello, 世界", 8))
    fmt.Printf("%q\n", trimLeftChars("Hello, 世界", 9))
    fmt.Printf("%q\n", trimLeftChars("Hello, 世界", 10))
}

: https://play.golang.org/p/ECAHl2FqdhR

:

""
""
""
"ello"
"界"

"Hello, 世界"
"Hello, 世界"
"ello, 世界"
"世界"
"界"
""
""

:

Go

Unicode UTF-8 FAQ

+14

This works for me:

package main

import "fmt"

func main() {
    input := "abcd"
    fmt.Println(input[1:])    
}

Output:

bcd

Code on Go Playground: https://play.golang.org/p/iTv7RpML3LO

-1
source

Source: https://habr.com/ru/post/1693664/


All Articles