Skip to main content
Code Review

Return to Question

replaced http://codereview.stackexchange.com/ with https://codereview.stackexchange.com/
Source Link

As an exercise I repeated this Java question, but in Go: Convert string to mixed case Convert string to mixed case

As an exercise I repeated this Java question, but in Go: Convert string to mixed case

As an exercise I repeated this Java question, but in Go: Convert string to mixed case

Tweeted twitter.com/StackCodeReview/status/726807663653298177
Source Link
rolfl
  • 98.1k
  • 17
  • 219
  • 419

Alternate letters to UpperCase

As an exercise I repeated this Java question, but in Go: Convert string to mixed case

The objective is for every second letter to be converted to uppercase.

Go string processing is relatively new to me, and I am looking for feedback on the use of the unicode package, any other go language or library features I should be using, and of course, issues with style, convention, or possible bugs.

I have put the following in the playground as well.

package kata
import (
 "unicode"
)
// AlternateCase will return the input string modified such that alternate letters are transformed to uppercase.
//
// Note that non-letters are ignored, so in the input string `a!b` the `!` is ignored, so `b` is the second letter.
// The result of AlternateCase on `a!b` is `A!b`.
func AlternateCase(input string) string {
 runes := make([]rune, 0, len(input))
 var upper bool
 for _, c := range input {
 if unicode.IsLetter(c) {
 upper = !upper
 if upper {
 c = unicode.ToUpper(c)
 }
 }
 runes = append(runes, c)
 }
 return string(runes)
}

I have also written some test cases, and a documentation example:

package kata
import (
 "fmt"
 "testing"
)
func TestAlternateCase(t *testing.T) {
 cases := []struct{ input, output string }{
 {"hello, world!", "HeLlO, wOrLd!"},
 {"a!b", "A!b"},
 {"AAAA", "AAAA"},
 {"", ""},
 {"h", "H"},
 {"!h", "!H"},
 {"日本語", "日本語"},
 {"f日u本b語ar", "F日U本B語Ar"},
 }
 for _, c := range cases {
 got := AlternateCase(c.input)
 if got != c.output {
 t.Errorf("For input '%v' expect '%v' but got '%v'", c.input, c.output, got)
 }
 }
}
func ExampleAlternateCase() {
 hi := "hello, world!"
 fmt.Printf("The AlternateCase of '%v' is '%v'\n", hi, AlternateCase(hi))
 // Output: The AlternateCase of 'hello, world!' is 'HeLlO, wOrLd!'
}

I am looking for feedback on the test mechanisms as well.

lang-golang

AltStyle によって変換されたページ (->オリジナル) /