Home > Back-end >  Accessing strings contained in slice
Accessing strings contained in slice

Time:12-17

I am working on some coding exercises to better understand Go. A given exercise instructs me to create a program that will accept user input as follows:

  • The first line specifies how many strings will be provided as input on separate lines
  • The subsequent N lines will each be single strings

I am to output the characters corresponding to even and odd indices of each string separated by a space, and each string on it's separate line.

Example Input:

2
foo_bar
fizz_buzz

Should Output:

fobr o_a
fz_uz izbz

But in my program accessing a slice of strings returns an empty string:

package main

import (
    "fmt"
)

func main() {
    // read an integer describing how many strings will be input
    var num_strings int
    fmt.Scan(&num_strings)

    // create a slice of strings to hold provided strings
    strings := make([]string, num_strings)

    // add provided strings to slice
    for i := 0; i < num_strings; i   {
        var temp string
        fmt.Scan(&temp)
        strings = append(strings, temp)
    }

    // check that strings have been appended
    fmt.Println("Strings:", strings)

    // check that strings can be accessed
    for i := 0; i < num_strings; i   {
        fmt.Println(i, strings[i]) // only i prints, not strings[i]
    }

    // loop over all strings
    for i := 0; i < num_strings; i   {

        // if string index is even print the char
        for index, val := range strings[i] {
            if index%2 == 0 {
                fmt.Print(val)
            }
        }

        fmt.Print(" ")

        // if string index is odd print the char
        for index, val := range strings[i] {
            if index%2 != 0 {
                fmt.Print(val)
            }
        }

        // newline for next string
        fmt.Print("\n")
    }
}

2
foo_bar
fizz_buzz
Strings: [  foo_bar fizz_buzz]
0 
1 
 
 

CodePudding user response:

Because when you make your strings slice, you're creating a slice with both a capacity and length of n. So when you append to it, you're increasing the length of the slice:

screen shot

Change this bit of code:

// create a slice of strings to hold provided strings
strings := make([]string, num_strings)

// add provided strings to slice
for i := 0; i < num_strings; i   {
  var temp string
  fmt.Scan(&temp)
  strings = append(strings, temp)
}

to either:

// create a slice of strings to hold provided strings
strings := []{}

// add provided strings to slice
for i := 0; i < num_strings; i   {
  var temp string
  fmt.Scan(&temp)
  strings = append(strings, temp)
}

Or

// create a slice of strings to hold provided strings
strings := make([]string, num_strings)

// add provided strings to slice
for i := 0; i < num_strings; i   {
  var temp string
  fmt.Scan(&temp)
  strings[i] = temp
}

And you should be good.

  •  Tags:  
  • go
  • Related