简体   繁体   English

如何在 Go 中反转字符串?

[英]How to reverse a string in Go?

我们如何在 Go 中反转一个简单的字符串?

In Go1 rune is a builtin type.在 Go1 中,符文是一种内置类型。

func Reverse(s string) string {
    runes := []rune(s)
    for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
        runes[i], runes[j] = runes[j], runes[i]
    }
    return string(runes)
}

Russ Cox, on the golang-nuts mailing list , suggests 在 golang-nuts 邮件列表中Russ Cox建议

package main 
import "fmt"
func main() { 
        input := "The quick brown 狐 jumped over the lazy 犬" 
        // Get Unicode code points. 
        n := 0
        rune := make([]rune, len(input))
        for _, r := range input { 
                rune[n] = r
                n++
        } 
        rune = rune[0:n]
        // Reverse 
        for i := 0; i < n/2; i++ { 
                rune[i], rune[n-1-i] = rune[n-1-i], rune[i] 
        } 
        // Convert back to UTF-8. 
        output := string(rune)
        fmt.Println(output)
}

This works, without all the mucking about with functions:这是有效的,而无需考虑函数:

func Reverse(s string) (result string) {
  for _,v := range s {
    result = string(v) + result
  }
  return 
}

From Go example projects: golang/example/stringutil/reverse.go , by Andrew Gerrand来自Go 示例项目: golang/example/stringutil/reverse.go ,作者 Andrew Gerrand

/*
Copyright 2014 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
     http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

// Reverse returns its argument string reversed rune-wise left to right.
func Reverse(s string) string {
    r := []rune(s)
    for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {
        r[i], r[j] = r[j], r[i]
    }
    return string(r)
}

Go Playground for reverse a string Go Playground 反转字符串

After reversing string "bròwn", the correct result should be "nwòrb", not "nẁorb".反转字符串“bròwn”后,正确的结果应该是“nwòrb”,而不是“nẁorb”。
Note the grave above the letter o.注意字母 o 上方的坟墓。


For preserving Unicode combining characters such as "as⃝df̅" with reverse result "f̅ds⃝a",为了保留 Unicode 组合字符,例如“as⃝df̅”与反向结果“f̅ds⃝a”,
please refer to another code listed below:请参考下面列出的另一个代码:

http://rosettacode.org/wiki/Reverse_a_string#Go http://rosettacode.org/wiki/Reverse_a_string#Go

This works on unicode strings by considering 2 things:通过考虑两件事,这适用于 unicode 字符串:

  • range works on string by enumerating unicode characters range通过枚举 unicode 字符来处理字符串
  • string can be constructed from int slices where each element is a unicode character. string 可以从 int 切片构造,其中每个元素都是一个 unicode 字符。

So here it goes:所以这里是这样的:

func reverse(s string) string {
    o := make([]int, utf8.RuneCountInString(s));
    i := len(o);
    for _, c := range s {
        i--;
        o[i] = c;
    }
    return string(o);
}

There are too many answers here.这里的答案太多了。 Some of them are clear duplicates.其中一些是明显的重复。 But even from the left one, it is hard to select the best solution.但即使从左边的一个,也很难选择最好的解决方案。

So I went through the answers, thrown away the one that does not work for unicode and also removed duplicates.所以我浏览了答案,扔掉了那些不适用于 unicode 的答案,并删除了重复项。 I benchmarked the survivors to find the fastest.我对幸存者进行了基准测试以找到最快的。 So here are the results with attribution (if you notice the answers that I missed, but worth adding, feel free to modify the benchmark):因此,以下是归因结果(如果您注意到我遗漏的答案,但值得添加,请随时修改基准):

Benchmark_rmuller-4   100000         19246 ns/op
Benchmark_peterSO-4    50000         28068 ns/op
Benchmark_russ-4       50000         30007 ns/op
Benchmark_ivan-4       50000         33694 ns/op
Benchmark_yazu-4       50000         33372 ns/op
Benchmark_yuku-4       50000         37556 ns/op
Benchmark_simon-4       3000        426201 ns/op

So here is the fastest method by rmuller :所以这是rmuller 最快的方法

func Reverse(s string) string {
    size := len(s)
    buf := make([]byte, size)
    for start := 0; start < size; {
        r, n := utf8.DecodeRuneInString(s[start:])
        start += n
        utf8.EncodeRune(buf[size-start:], r)
    }
    return string(buf)
}

For some reason I can't add a benchmark, so you can copy it from PlayGround (you can't run tests there).出于某种原因,我无法添加基准测试,因此您可以从PlayGround复制它(您不能在那里运行测试)。 Rename it and run go test -bench=.重命名并运行go test -bench=.

I noticed this question when Simon posted his solution which, since strings are immutable, is very inefficient.Simon发布他的解决方案时,我注意到了这个问题,因为字符串是不可变的,所以效率非常低。 The other proposed solutions are also flawed;其他提议的解决方案也有缺陷; they don't work or they are inefficient.它们不起作用或效率低下。

Here's an efficient solution that works, except when the string is not valid UTF-8 or the string contains combining characters.这是一个有效的解决方案,除非字符串不是有效的 UTF-8 或字符串包含组合字符。

package main

import "fmt"

func Reverse(s string) string {
    n := len(s)
    runes := make([]rune, n)
    for _, rune := range s {
        n--
        runes[n] = rune
    }
    return string(runes[n:])
}

func main() {
    fmt.Println(Reverse(Reverse("Hello, 世界")))
    fmt.Println(Reverse(Reverse("The quick brown 狐 jumped over the lazy 犬")))
}

I wrote the following Reverse function which respects UTF8 encoding and combined characters:我编写了以下尊重 UTF8 编码和组合字符的Reverse函数:

// Reverse reverses the input while respecting UTF8 encoding and combined characters
func Reverse(text string) string {
    textRunes := []rune(text)
    textRunesLength := len(textRunes)
    if textRunesLength <= 1 {
        return text
    }

    i, j := 0, 0
    for i < textRunesLength && j < textRunesLength {
        j = i + 1
        for j < textRunesLength && isMark(textRunes[j]) {
            j++
        }

        if isMark(textRunes[j-1]) {
            // Reverses Combined Characters
            reverse(textRunes[i:j], j-i)
        } 

        i = j
    }

    // Reverses the entire array
    reverse(textRunes, textRunesLength)

    return string(textRunes)
}

func reverse(runes []rune, length int) {
    for i, j := 0, length-1; i < length/2; i, j = i+1, j-1 {
        runes[i], runes[j] = runes[j], runes[i]
    }
}

// isMark determines whether the rune is a marker
func isMark(r rune) bool {
    return unicode.Is(unicode.Mn, r) || unicode.Is(unicode.Me, r) || unicode.Is(unicode.Mc, r)
}

I did my best to make it as efficient and readable as possible.我尽我所能使它尽可能高效和可读。 The idea is simple, traverse through the runes looking for combined characters then reverse the combined characters' runes in-place.这个想法很简单,遍历符文寻找组合字符,然后就地反转组合字符的符文。 Once we have covered them all, reverse the runes of the entire string also in-place.一旦我们将它们全部覆盖,将整个字符串的符文也原地反转。

Say we would like to reverse this string bròwn .假设我们想反转这个字符串bròwn The ò is represented by two runes, one for the o and one for this unicode \́a that represents the "grave". ò由两个符文表示,一个代表o ,一个代表这个代表“坟墓”的 unicode \́a

For simplicity, let's represent the string like this bro'wn .为简单起见,让我们表示像这个bro'wn的字符串。 The first thing we do is look for combined characters and reverse them.我们做的第一件事是寻找组合字符并将它们反转。 So now we have the string br'own .所以现在我们有了字符串br'own Finally, we reverse the entire string and end up with nwo'rb .最后,我们反转整个字符串并以nwo'rb结束。 This is returned to us as nwòrb这是作为nwòrb返回给我们的

You can find it here https://github.com/shomali11/util if you would like to use it.如果你想使用它,你可以在这里找到它https://github.com/shomali11/util

Here are some test cases to show a couple of different scenarios:这里有一些测试用例来展示几个不同的场景:

func TestReverse(t *testing.T) {
    assert.Equal(t, Reverse(""), "")
    assert.Equal(t, Reverse("X"), "X")
    assert.Equal(t, Reverse("b\u0301"), "b\u0301")
    assert.Equal(t, Reverse("😎⚽"), "⚽😎")
    assert.Equal(t, Reverse("Les Mise\u0301rables"), "selbare\u0301siM seL")
    assert.Equal(t, Reverse("ab\u0301cde"), "edcb\u0301a")
    assert.Equal(t, Reverse("This `\xc5` is an invalid UTF8 character"), "retcarahc 8FTU dilavni na si `�` sihT")
    assert.Equal(t, Reverse("The quick bròwn 狐 jumped over the lazy 犬"), "犬 yzal eht revo depmuj 狐 nwòrb kciuq ehT")
}
//Reverse reverses string using strings.Builder. It's about 3 times faster
//than the one with using a string concatenation
func Reverse(in string) string {
    var sb strings.Builder
    runes := []rune(in)
    for i := len(runes) - 1; 0 <= i; i-- {
        sb.WriteRune(runes[i])
    }
    return sb.String()
}


//Reverse reverses string using string
func Reverse(in string) (out string) {
    for _, r := range in {
        out = string(r) + out
    }
    return
}

BenchmarkReverseStringConcatenation-8   1000000 1571 ns/op  176 B/op    29 allocs/op
BenchmarkReverseStringsBuilder-8        3000000 499 ns/op   56 B/op 6 allocs/op

Using strings.Builder is about 3 times faster than using string concatenation使用 strings.Builder 比使用字符串连接快大约 3 倍

Here is quite different, I would say more functional approach, not listed among other answers:这是完全不同的,我会说更多功能方法,未在其他答案中列出:

func reverse(s string) (ret string) {
    for _, v := range s {
        defer func(r rune) { ret += string(r) }(v)
    }
    return
}

Building on Stephan202's original suggestion, and appears to work for unicode strings:基于 Stephan202 的原始建议,似乎适用于 unicode 字符串:

import "strings";

func Reverse( orig string ) string {
    var c []string = strings.Split( orig, "", 0 );

    for i, j := 0, len(c)-1; i < j; i, j = i+1, j-1 {
        c[i], c[j] = c[j], c[i]
    }

    return strings.Join( c, "" );
}

Alternate, not using strings package, but not 'unicode-safe':或者,不使用字符串包,但不使用“unicode-safe”:

func Reverse( s string ) string {
    b := make([]byte, len(s));
    var j int = len(s) - 1;
    for i := 0; i <= j; i++ {
        b[j-i] = s[i]
    }

    return string ( b );
}

This is the fastest implementation这是最快的实现

func Reverse(s string) string {
    size := len(s)
    buf := make([]byte, size)
    for start := 0; start < size; {
        r, n := utf8.DecodeRuneInString(s[start:])
        start += n
        utf8.EncodeRune(buf[size-start:], r)
    }
    return string(buf)
}

const (
    s       = "The quick brown 狐 jumped over the lazy 犬"
    reverse = "犬 yzal eht revo depmuj 狐 nworb kciuq ehT"
)

func TestReverse(t *testing.T) {
    if Reverse(s) != reverse {
        t.Error(s)
    }
}

func BenchmarkReverse(b *testing.B) {
    for i := 0; i < b.N; i++ {
        Reverse(s)
    }
}

A simple stroke with rune :一个简单的rune笔画:

func ReverseString(s string) string {
    runes := []rune(s)
    size := len(runes)
    for i := 0; i < size/2; i++ {
        runes[size-i-1], runes[i] = runes[i],  runes[size-i-1]
    }
    return string(runes)
}

func main() {
    fmt.Println(ReverseString("Abcdefg 汉语 The God"))
}
: doG ehT 语汉 gfedcbA

You could also import an existing implementation:您还可以导入现有的实现:

import "4d63.com/strrev"

Then:然后:

strrev.Reverse("abåd") // returns "dåba"

Or to reverse a string including unicode combining characters:或者反转包含 unicode 组合字符的字符串:

strrev.ReverseCombining("abc\u0301\u031dd") // returns "d\u0301\u031dcba"

These implementations supports correct ordering of unicode multibyte and combing characters when reversed.这些实现在反转时支持 unicode 多字节和组合字符的正确排序。

Note: Built-in string reverse functions in many programming languages do not preserve combining, and identifying combining characters requires significantly more execution time.注意:许多编程语言中的内置字符串反转函数不保留组合,并且识别组合字符需要更多的执行时间。

If you need to handle grapheme clusters, use unicode or regexp module.如果您需要处理字素簇,请使用 unicode 或 regexp 模块。

package main

import (
  "unicode"
  "regexp"
)

func main() {
    str := "\u0308" + "a\u0308" + "o\u0308" + "u\u0308"
    println("u\u0308" + "o\u0308" + "a\u0308" + "\u0308" == ReverseGrapheme(str))
    println("u\u0308" + "o\u0308" + "a\u0308" + "\u0308" == ReverseGrapheme2(str))
}

func ReverseGrapheme(str string) string {

  buf := []rune("")
  checked := false
  index := 0
  ret := "" 

    for _, c := range str {

        if !unicode.Is(unicode.M, c) {

            if len(buf) > 0 {
                ret = string(buf) + ret
            }

            buf = buf[:0]
            buf = append(buf, c)

            if checked == false {
                checked = true
            }

        } else if checked == false {
            ret = string(append([]rune(""), c)) + ret
        } else {
            buf = append(buf, c)
        }

        index += 1
    }

    return string(buf) + ret
}

func ReverseGrapheme2(str string) string {
    re := regexp.MustCompile("\\PM\\pM*|.")
    slice := re.FindAllString(str, -1)
    length := len(slice)
    ret := ""

    for i := 0; i < length; i += 1 {
        ret += slice[length-1-i]
    }

    return ret
}

This code preserves sequences of combining characters intact, and should work with invalid UTF-8 input too.此代码完整地保留了组合字符的序列,并且也应该适用于无效的 UTF-8 输入。

package stringutil
import "code.google.com/p/go.text/unicode/norm"

func Reverse(s string) string {
    bound := make([]int, 0, len(s) + 1)

    var iter norm.Iter
    iter.InitString(norm.NFD, s)
    bound = append(bound, 0)
    for !iter.Done() {
        iter.Next()
        bound = append(bound, iter.Pos())
    }
    bound = append(bound, len(s))
    out := make([]byte, 0, len(s))
    for i := len(bound) - 2; i >= 0; i-- {
        out = append(out, s[bound[i]:bound[i+1]]...)
    }
    return string(out)
}

It could be a little more efficient if the unicode/norm primitives allowed iterating through the boundaries of a string without allocating.如果 unicode/norm 原语允许在不分配的情况下遍历字符串的边界,则效率可能会更高一些。 See also https://code.google.com/p/go/issues/detail?id=9055 .另请参阅https://code.google.com/p/go/issues/detail?id=9055

It's assuredly not the most memory efficient solution, but for a "simple" UTF-8 safe solution the following will get the job done and not break runes.这肯定不是最节省内存的解决方案,但对于“简单”的 UTF-8 安全解决方案,以下内容将完成工作并且不会破坏符文。

It's in my opinion the most readable and understandable on the page.在我看来,它是页面上最易读和易懂的。

func reverseStr(str string) (out string) {
    for _, s := range str {
        out = string(s) + out
    }

    return
}

NOTE: This answer is from 2009, so there are probably better solutions out there by now.注意:这个答案来自 2009 年,所以现在可能有更好的解决方案。


Looks a bit 'roundabout', and probably not very efficient, but illustrates how the Reader interface can be used to read from strings.看起来有点“迂回”,可能效率不高,但说明了如何使用 Reader 接口从字符串中读取。 IntVectors also seem very suitable as buffers when working with utf8 strings.在处理 utf8 字符串时,IntVectors 似乎也非常适合作为缓冲区。

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.此解决方案绝对适用于 utf8 字符。

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());
}

The following two methods run faster than the fastest solution that preserve combining characters , though that's not to say I'm missing something in my benchmark setup.以下两种方法比保留组合字符的最快解决方案运行得更快,但这并不是说我在基准测试设置中遗漏了一些东西。

//input string s
bs := []byte(s)
var rs string
for len(bs) > 0 {
    r, size := utf8.DecodeLastRune(bs)
    rs += fmt.Sprintf("%c", r)
    bs = bs[:len(bs)-size]
} // rs has reversed string

Second method inspired by this方法二灵感

//input string s
bs := []byte(s)
cs := make([]byte, len(bs))
b1 := 0
for len(bs) > 0 {
    r, size := utf8.DecodeLastRune(bs)
    d := make([]byte, size)
    _ = utf8.EncodeRune(d, r)
    b1 += copy(cs[b1:], d)
    bs = bs[:len(bs) - size]
} // cs has reversed bytes
func Reverse(s string) string {
    r := []rune(s)
    var output strings.Builder
    for i := len(r) - 1; i >= 0; i-- {
        output.WriteString(string(r[i]))
    }

    return output.String()
}
func ReverseString(str string) string {
  output :=""
  for _, char := range str {
    output = string(char) + output
  }
  return output
}

// "Luizpa" -> "apziuL"
// "123日本語" -> "語本日321"
// "⚽😎" -> "😎⚽"
// "´a´b´c´" -> "´c´b´a´"

Simple, Sweet and Performant简单、甜美、高性能

func reverseStr(str string) string {
  strSlice := []rune(str)  //converting to slice of runes
  length := len(strSlice)

  for i := 0; i < (length / 2); i++ {
      strSlice[i], strSlice[length-i-1] = strSlice[length-i-1], strSlice[i]
  }
  return string(strSlice)  //converting back to string
}

Reversing a string by word is a similar process.按单词反转字符串是一个类似的过程。 First, we convert the string into an array of strings where each entry is a word.首先,我们将字符串转换为字符串数组,其中每个条目都是一个单词。 Next, we apply the normal reverse loop to that array.接下来,我们将正常的反向循环应用于该数组。 Finally, we smush the results back together into a string that we can return to the caller.最后,我们将结果合并成一个字符串,我们可以返回给调用者。

package main

import (
    "fmt"
    "strings"
)

func reverse_words(s string) string {
    words := strings.Fields(s)
    for i, j := 0, len(words)-1; i < j; i, j = i+1, j-1 {
        words[i], words[j] = words[j], words[i]
    }
    return strings.Join(words, " ")
}

func main() {
    fmt.Println(reverse_words("one two three"))
}

rune is a type, so use it.符文是一种类型,所以使用它。 Moreover, Go doesn't use semicolons.此外,Go 不使用分号。

func reverse(s string) string {
    l := len(s)
    m := make([]rune, l)

    for _, c := range s {
        l--
        m[l] = c
    }
    return string(m)
}

func main() {
    str := "the quick brown 狐 jumped over the lazy 犬"
    fmt.Printf("reverse(%s): [%s]\n", str, reverse(str))
}

A version which I think works on unicode.我认为适用于 unicode 的版本。 It is built on the utf8.Rune functions:它建立在 utf8.Rune 函数之上:

func Reverse(s string) string {
    b := make([]byte, len(s));
    for i, j := len(s)-1, 0; i >= 0; i-- {
        if utf8.RuneStart(s[i]) {
            rune, size := utf8.DecodeRuneInString(s[i:len(s)]);
            utf8.EncodeRune(rune, b[j:j+size]);
            j += size;
        }
    }
    return string(b);
}

try below code:试试下面的代码:

package main

import "fmt"

func reverse(s string) string {
    chars := []rune(s)
    for i, j := 0, len(chars)-1; i < j; i, j = i+1, j-1 {
        chars[i], chars[j] = chars[j], chars[i]
    }
    return string(chars)
}

func main() {
    fmt.Printf("%v\n", reverse("abcdefg"))
}

for more info check http://golangcookbook.com/chapters/strings/reverse/有关更多信息,请查看http://golangcookbook.com/chapters/strings/reverse/
and http://www.dotnetperls.com/reverse-string-gohttp://www.dotnetperls.com/reverse-string-go

For simple strings it possible to use such construction:对于简单的字符串,可以使用这样的结构:

func Reverse(str string) string {
    if str != "" {
        return Reverse(str[1:]) + str[:1]
    }
    return ""   
}
func reverseStr(b string) {
for _, v := range []rune(b) {
    defer fmt.Printf("%c", v)

}
 }

Defer is useful for this as it is LIFO - Last in First Out Defer 对此很有用,因为它是 LIFO - 后进先出

Strings are immutable object in golang, unlike C inplace reverse is not possible with golang.字符串在 golang 中是不可变的对象,与 C 不同,golang 不可能实现反向。 With C , you can do something like,使用 C ,你可以做类似的事情,

void reverseString(char *str) {
  int length = strlen(str)
  for(int i = 0, j = length-1; i < length/2; i++, j--)
  {
    char tmp = str[i];
    str[i] = str[j];
    str[j] = tmp;
  }
}

But with golang, following one, uses byte to convert the input into bytes first and then reverses the byte array once it is reversed, convert back to string before returning.但是对于golang,接下来是先使用字节将输入转换为字节,然后在反转后反转字节数组,在返回之前转换回字符串。 works only with non unicode type string.仅适用于非 unicode 类型字符串。

package main

import "fmt"

func main() {
    s := "test123 4"
    fmt.Println(reverseString(s))
}

func reverseString(s string) string {
    a := []byte(s)
    for i, j := 0, len(s)-1; i < j; i++ {
        a[i], a[j] = a[j], a[i]
        j--
    }
    return string(a)
}

Here is yet another solution:这是另一个解决方案:

func ReverseStr(s string) string {
    chars := []rune(s)
    rev := make([]rune, 0, len(chars))
    for i := len(chars) - 1; i >= 0; i-- {
        rev = append(rev, chars[i])
    }
    return string(rev)
}

However, yazu's solution above is more elegant since he reverses the []rune slice in place.然而,yazu 上面的解决方案更优雅,因为他将[]rune切片反转到位。

Yet Another Solution (tm) :另一个解决方案(tm):

package main 
import "fmt"

type Runes []rune

func (s Runes) Reverse() (cp Runes) {
    l := len(s); cp = make(Runes, l)
    // i <= 1/2 otherwise it will mess up with odd length strings
    for i := 0; i <= l/2; i++ { 
        cp[i], cp[l-1-i] = s[l-1-i], s[i] 
    }
    return cp
}

func (s Runes) String() string {
    return string(s)
}

func main() { 
    input := "The quick brown 狐 jumped over the lazy 犬 +odd" 
    r := Runes(input)
    output := r.Reverse()
    valid := string(output.Reverse()) == input
    fmt.Println(len(r), len(output), r, output.Reverse(), valid)
}
package reverseString

import "strings"

// ReverseString - output the reverse string of a given string s
func ReverseString(s string) string {

    strLen := len(s)

    // The reverse of a empty string is a empty string
    if strLen == 0 {
        return s
    }

    // Same above
    if strLen == 1 {
        return s
    }

    // Convert s into unicode points
    r := []rune(s)

    // Last index
    rLen := len(r) - 1

    // String new home
    rev := []string{}

    for i := rLen; i >= 0; i-- {
        rev = append(rev, string(r[i]))
    }

    return strings.Join(rev, "")
}

Test测试

package reverseString

import (
    "fmt"
    "strings"
    "testing"
)

func TestReverseString(t *testing.T) {

    s := "GO je úžasné!"
    r := ReverseString(s)

    fmt.Printf("Input: %s\nOutput: %s", s, r)

    revR := ReverseString(r)

    if strings.Compare(s, revR) != 0 {
        t.Errorf("Expecting: %s\n. Got: %s\n", s, revR)
    }
}

Output输出

Input: GO je úžasné!
Output: !énsažú ej OG
PASS
ok      github.com/alesr/reverse-string 0.098s
    func reverseString(someString string) string {
        runeString := []rune(someString)
        var reverseString string
        for i := len(runeString)-1; i >= 0; i -- {
            reverseString += string(runeString[i])
        }
        return reverseString
    }

Another hack is to use built-in language features, for example, defer :另一个技巧是使用内置语言功能,例如defer

package main

import "fmt"

func main() {
    var name string
    fmt.Scanln(&name)

    for _, char := range []rune(name) {
        defer fmt.Printf("%c", char) // <-- LIFO does it all for you
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM