Hi, I'm Ataias Reis

Programmer, made in Brazil, Alma mater University of Brasilia

30 days of code in Go: Day 6 - Let's review

Some challenges require us to review basic concepts to make them work. This one is no different, but the main purpose of it is to be a review! The goal is to separate the characters of a string. The even-indexed characters will form a string and the odd-indexed characters will form another. These two strings must be printed to the screen with a space between them. Not hard, but an important review. Solution below.

package main

import (
 "bufio"
 "fmt"
 "os"
)

func main() {
 scanner := bufio.NewReader(os.Stdin)
 var N int
 fmt.Scan(&N)
 for j := 0; j < N; j++ {
  var input string
  input, _ = scanner.ReadString('\n')

  for i := 0; i < len(input); i += 2 {
   if input[i] != '\n' {
    fmt.Printf("%c", input[i])
   }
  }
  fmt.Printf(" ")
  for i := 1; i < len(input); i += 2 {
   if input[i] != '\n' {
    fmt.Printf("%c", input[i])
   }
  }
  fmt.Printf("\n")
 }
}

After solving it, I noticed there were a couple catches I wasn’t aware of. First of, the string input has a newline character \n that was causing my output to appear in two lines like:

$ ./day_06
# input
1
Ataias
# output
Aaa
 tis

This is way I added an if checking if the last character was a new line. Initially I wrote it inside the loops, but I noticed this was just overkill (inefficient) and I moved it outside. With the final solution, I had the following input/output:

$ ./day_06
# number of strings (input)
2
# first string (input)
Ataias
# first string (output)
Aaa tis
# second string (input)
Amanda
# second string (output)
Aad mna

That’s all for this day of coding in Go! Hope you enjoyed it! If you liked it, please comment!

Tags
comments powered by Disqus