How to reverse a string in Go?

前端 未结 28 2021
天涯浪人
天涯浪人 2020-12-04 06:45

How can we reverse a simple string in Go?

28条回答
  •  孤街浪徒
    2020-12-04 07:38

    NOTE: This answer is from 2009, so there are probably better solutions out there by now.


    Looks a bit 'roundabout', and probably not very efficient, but illustrates how the Reader interface can be used to read from strings. IntVectors also seem very suitable as buffers when working with utf8 strings.

    It would be even shorter when leaving out the 'size' part, and insertion into the vector by Insert, but I guess that would be less efficient, as the whole vector then needs to be pushed back by one each time a new rune is added.

    This solution definitely works with utf8 characters.

    package main
    
    import "container/vector";
    import "fmt";
    import "utf8";
    import "bytes";
    import "bufio";
    
    
    func
    main() {
        toReverse := "Smørrebrød";
        fmt.Println(toReverse);
        fmt.Println(reverse(toReverse));
    }
    
    func
    reverse(str string) string {
        size := utf8.RuneCountInString(str);
        output := vector.NewIntVector(size);
        input := bufio.NewReader(bytes.NewBufferString(str));
        for i := 1; i <= size; i++ {
            rune, _, _ := input.ReadRune();
            output.Set(size - i, rune);
        }
        return string(output.Data());
    }
    

提交回复
热议问题