如何在Golang的字符串中每X个字符插入一个字符? [英] How to insert a Character every X Characters in a String in Golang?

查看:1035
本文介绍了如何在Golang的字符串中每X个字符插入一个字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目标:在Golang字符串中的每x个字符中插入一个字符

Aim: to insert a character every x characters in a string in Golang

输入: helloworldhelloworldhelloworld

预期输出: hello-world-hello-world -hello-world

尝试

尝试一个

package main

import (
    "fmt"
    "strings"
)

func main() {
    s := "helloworldhelloworldhelloworld"

    s = strings.Replace(s, "world", ",", -1)
    fmt.Println(s)
}

结果: hello,hello,hello,

尝试两个


  1. 字符数计数

  2. 循环

  3. 如果X = 5,则插入-

  1. Count number of characters
  2. For loop
  3. If X=5 then insert a -






尝试三个


  1. 扫描合并和乔n

问题

原因尝试2和3目前不包含代码段的原因是,我仍在思考应该使用哪种方法在Golang中的字符串中每X个字符插入一个字符。

The reason that attempts two and three do not contain code snippets at the moment is that I am still thinking what approach should be used to insert a character every X characters in a string in Golang.

推荐答案

https://play.golang.org/p/HEGbe7radf

此函数仅在第N个元素中插入-

This function just inserts '-' each Nth element

func insertNth(s string,n int) string {
    var buffer bytes.Buffer
    var n_1 = n - 1
    var l_1 = len(s) - 1
    for i,rune := range s {
       buffer.WriteRune(rune)
       if i % n == n_1 && i != l_1  {
          buffer.WriteRune('-')
       }
    }
    return buffer.String()
}

这篇关于如何在Golang的字符串中每X个字符插入一个字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆