github.com/wangyougui/gf/v2@v2.6.5/text/gstr/gstr_z_unit_replace_test.go (about) 1 // Copyright GoFrame Author(https://goframe.org). All Rights Reserved. 2 // 3 // This Source Code Form is subject to the terms of the MIT License. 4 // If a copy of the MIT was not distributed with this file, 5 // You can obtain one at https://github.com/wangyougui/gf. 6 7 // go test *.go -bench=".*" 8 9 package gstr_test 10 11 import ( 12 "testing" 13 14 "github.com/wangyougui/gf/v2/frame/g" 15 "github.com/wangyougui/gf/v2/test/gtest" 16 "github.com/wangyougui/gf/v2/text/gstr" 17 ) 18 19 func Test_Replace(t *testing.T) { 20 gtest.C(t, func(t *gtest.T) { 21 s1 := "abcdEFG乱入的中文abcdefg" 22 t.Assert(gstr.Replace(s1, "ab", "AB"), "ABcdEFG乱入的中文ABcdefg") 23 t.Assert(gstr.Replace(s1, "EF", "ef"), "abcdefG乱入的中文abcdefg") 24 t.Assert(gstr.Replace(s1, "MN", "mn"), s1) 25 26 t.Assert(gstr.ReplaceByArray(s1, g.ArrayStr{ 27 "a", "A", 28 "A", "-", 29 "a", 30 }), "-bcdEFG乱入的中文-bcdefg") 31 32 t.Assert(gstr.ReplaceByMap(s1, g.MapStrStr{ 33 "a": "A", 34 "G": "g", 35 }), "AbcdEFg乱入的中文Abcdefg") 36 }) 37 } 38 39 func Test_ReplaceI_1(t *testing.T) { 40 gtest.C(t, func(t *gtest.T) { 41 s1 := "abcd乱入的中文ABCD" 42 s2 := "a" 43 t.Assert(gstr.ReplaceI(s1, "ab", "aa"), "aacd乱入的中文aaCD") 44 t.Assert(gstr.ReplaceI(s1, "ab", "aa", 0), "abcd乱入的中文ABCD") 45 t.Assert(gstr.ReplaceI(s1, "ab", "aa", 1), "aacd乱入的中文ABCD") 46 47 t.Assert(gstr.ReplaceI(s1, "abcd", "-"), "-乱入的中文-") 48 t.Assert(gstr.ReplaceI(s1, "abcd", "-", 1), "-乱入的中文ABCD") 49 50 t.Assert(gstr.ReplaceI(s1, "abcd乱入的", ""), "中文ABCD") 51 t.Assert(gstr.ReplaceI(s1, "ABCD乱入的", ""), "中文ABCD") 52 53 t.Assert(gstr.ReplaceI(s2, "A", "-"), "-") 54 t.Assert(gstr.ReplaceI(s2, "a", "-"), "-") 55 56 t.Assert(gstr.ReplaceIByArray(s1, g.ArrayStr{ 57 "abcd乱入的", "-", 58 "-", "=", 59 "a", 60 }), "=中文ABCD") 61 62 t.Assert(gstr.ReplaceIByMap(s1, g.MapStrStr{ 63 "ab": "-", 64 "CD": "=", 65 }), "-=乱入的中文-=") 66 }) 67 } 68 69 func Test_ReplaceI_2(t *testing.T) { 70 gtest.C(t, func(t *gtest.T) { 71 t.Assert(gstr.ReplaceI("aaa", "A", "-a-"), `-a--a--a-`) 72 t.Assert(gstr.ReplaceI("aaaa", "AA", "-"), `--`) 73 t.Assert(gstr.ReplaceI("a a a", "A", "b"), `b b b`) 74 t.Assert(gstr.ReplaceI("aaaaaa", "aa", "a"), `aaa`) 75 t.Assert(gstr.ReplaceI("aaaaaa", "AA", "A"), `AAA`) 76 t.Assert(gstr.ReplaceI("aaa", "A", "AA"), `AAAAAA`) 77 t.Assert(gstr.ReplaceI("aaa", "A", "AA"), `AAAAAA`) 78 t.Assert(gstr.ReplaceI("a duration", "duration", "recordduration"), `a recordduration`) 79 }) 80 // With count parameter. 81 gtest.C(t, func(t *gtest.T) { 82 t.Assert(gstr.ReplaceI("aaaaaa", "aa", "a", 2), `aaaa`) 83 t.Assert(gstr.ReplaceI("aaaaaa", "AA", "A", 1), `Aaaaa`) 84 t.Assert(gstr.ReplaceI("aaaaaa", "AA", "A", 3), `AAA`) 85 t.Assert(gstr.ReplaceI("aaaaaa", "AA", "A", 4), `AAA`) 86 t.Assert(gstr.ReplaceI("aaa", "A", "AA", 2), `AAAAa`) 87 t.Assert(gstr.ReplaceI("aaa", "A", "AA", 3), `AAAAAA`) 88 t.Assert(gstr.ReplaceI("aaa", "A", "AA", 4), `AAAAAA`) 89 }) 90 }