0
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?

More than 3 years have passed since last update.

go langの文字列操作 決定版?

Last updated at Posted at 2020-05-10
package main

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

func main() {
	integer := "12345"
	str := "abcd"

	//取得
	fmt.Println(integer[0]) //rune番号
	fmt.Println(string([]rune(str)[0])) //a
	fmt.Println(str[0:1]) //a
	fmt.Println(str[0:2]) //ab
	str += ""
	str += "e"
	fmt.Println(str) //abcde
	fmt.Println(len(str)) //5  空文字はlengthには加算されない

	//最後の要素
	fmt.Println(str[len(str)-1])  //rune 101
	fmt.Println(string([]rune(str)[len(str)-1])) //e
	fmt.Println(str[len(str)-1:]) //e
	fmt.Println(str[len(str)-2:]) //de
	fmt.Println(str[:len(str)-1]) //abcd

	//sort
	str += "b"
	fmt.Println(str) //abcdeb
	s := strings.Split(str,"") //[]sliceになる
	fmt.Println(s) //[a b c d e b]
	sort.Strings(s)
	fmt.Println(s) //[a b b c d e]
	str = strings.Join(s,"")
	fmt.Println(str) //abbcde

	//削除
	//基本空文字を入れると消える + 一度 []stringへ変換する
	s= strings.Split(str,"")
	s[len(str)-1] = ""
	str = strings.Join(s,"")
	fmt.Println(str) //abbcd

	//置換
	s= strings.Split(str,"")
	s = append(s[:len(str)-1],"h")
	fmt.Println(s) //[a b b c h]
	s = append(s[:len(str)-2],"d")
	fmt.Println(s) //[a b b d]

    //初めの要素から入れ直す
	s = append(s[:0],"e")
	fmt.Println(s) //[e]
	s = append(s[0:],"x")
	fmt.Println(s) //[e,x]
	str = strings.Join(s,"")


	str = "abcde" 	//一度戻す
	fmt.Println(str) //abcd
	s = strings.Split(str,"")
	s = s[:len(s)-1] //末尾削除
	fmt.Println(s) //[a b c d]
	s = append(s[:1],s[2:]...) 	//bのみ削除
	fmt.Println(s) //[a c d]
}

0
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
0
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?