2015-10-21 92 views
0

我有串這樣ClientLovesProcess我需要除了第一個大寫字母每個大寫字母之間添加一個空格,因此最終的結果會是這樣Client Loves Process添加uppsercase字母

我不認爲golang具有之間的空間最好的字符串支持,但是這是我在想繞了:

首先遍歷每個字母的所以是這樣的:

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 
    } 
} 

問題是我不知道如何來檢查字母較低或者大寫。我檢查了字符串手冊,但他們沒有一些有它的功能。什麼是另一種方法來完成這項工作呢?

回答

7

你要找的功能是unicode.IsUpper(r rune) bool

我會使用bytes.Buffer,這樣你就不會進行一堆字符串連接,這會導致額外的不必要的分配。

下面是一個實現:

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() 
} 

並有play link

0

您可以使用unicode軟件包測試大寫字母。這是我的解決方案:

playground

package main 

import (
    "fmt" 
    "strings" 
    "unicode" 
) 

func main() { 
    name := "ClientLovesProcess" 
    newName := "" 
    for _, c := range name { 

     if unicode.IsUpper(c){ 
      newName += " " 
     } 
     newName += string(c) 
    } 
    newName = strings.TrimSpace(newName) // get rid of space on edges. 
    fmt.Println(newName) 
}