douyi6818 2015-10-21 16:10
浏览 81
已采纳

在大写字母之间添加空格

I have string like this ClientLovesProcess I need to add a space between each uppercase letter except for the first uppercase letter so the end result would be this Client Loves Process

I don't think golang has the best string support but this is how I was thinking about going about it:

First loop through each letter so something like this:

name := "ClientLovesProcess"

wordLength := len(name)

for i := 0; i < wordLength; i++ {
    letter := string([]rune(name)[i])

    // then in here I would like to check
   // if the letter is upper or lowercase

   if letter == uppercase{
       // then break the string and add a space
   }
}

The issue is I don't know how to check if a letter is lower or uppercase in go. I checked the strings manual but they don't some to have a function for it. What would be another approach to get this done with go?

  • 写回答

2条回答 默认 最新

  • duankuang7928 2015-10-21 16:20
    关注

    The function you're looking for is unicode.IsUpper(r rune) bool.

    I would use a bytes.Buffer so that you're not doing a bunch of string concatenations, which results in extra unnecessary allocations.

    Here's an implementation:

    func addSpace(s string) string {
        buf := &bytes.Buffer{}
        for i, rune := range s {
            if unicode.IsUpper(rune) && i > 0 {
                buf.WriteRune(' ')
            }
            buf.WriteRune(rune)
        }
        return buf.String()
    }
    

    And a play link.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题