1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[Go][tips][ProblemSolver] 文字列を辞書順 sort

Last updated at Posted at 2024-11-03

tipsです。

文字列を辞書順ソート

お題 「"defacb"を辞書順に並べ替えて、"abcedf"にしてください。」

goにはchar型がないです。代わりに、[]byte[]runeを使用します。

[]runeをちゃんと理解したい人は参考サイトへ。

方法1 []rune型を使用

package main

import (
	"fmt"
	"sort"
	"strings"
)

func main(){
	var s string
	s = "defacb"

	runes := []rune(s)
	// stringの文字列を辞書順並べ替え
	sort.Slice(runes, func(i, j int) bool {
		return runes[i] < runes[j]
	})
    fmt.Println(string(runes))
}
abcdef

方法2 charっぽく並べ替え

  1. strings.Split("defacb", "")として1文字ずつのsliceにして並べ替える。
  2. 並べ替え操作を施した1文字ずつのsliceをくっつける

です。

package main

import (
	"fmt"
	"sort"
	"strings"
)

func main(){
	var s string
	s = "defacb"

	chars := strings.Split(s, "")
	// stringの文字列を辞書順並べ替え
	sort.Slice(chars, func(i, j int) bool {
		return chars[i] < chars[j]
	})
    fmt.Println(strings.Join(chars, ""))
}
abcdef

参考

Goのruneを理解するためのUnicode知識
GoのSliceをSortする(sort.Sliceとsort.SliceStable)
golangでstringをsliceのように扱う
Goで回文判定

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?