search
HomeBackend DevelopmentGolangAccess the string contained in a slice

Access the string contained in a slice

php editor Xiaoxin is here to introduce how to access the strings contained in the slice. In PHP, slicing refers to the operation of intercepting a part of characters from a string. By accessing the strings in the slice, we can get the required data or perform other operations. When using slicing, we need to specify the starting position and ending position to get the corresponding string. Mastering the use of slices will bring great convenience to our development work. Next, let us learn in detail how to access the string contained in the slice!

Question content

I am doing some coding exercises to understand go better. The given exercise instructs me to create a program that accepts user input as follows:

  • The first line specifies how many strings will be provided as input on separate lines
  • Each of the next n lines is a single string

I want to output the characters corresponding to the even and odd indexes of each string, separated by spaces, and with each string on a separate line.

Input example:

2
foo_bar
fizz_buzz

should output:

fobr o_a
fz_uz izbz

But accessing the string slice in my program 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

Workaround

Because when you make strings slice you are creating a capacity and length is a slice of n. So when you append to it, you increase the length of the slice:

Change this 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)
}

arrive:

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

You should be on your best behavior.

The above is the detailed content of Access the string contained in a slice. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:stackoverflow. If there is any infringement, please contact admin@php.cn delete
init Functions and Side Effects: Balancing Initialization with Maintainabilityinit Functions and Side Effects: Balancing Initialization with MaintainabilityApr 26, 2025 am 12:23 AM

Toensureinitfunctionsareeffectiveandmaintainable:1)Minimizesideeffectsbyreturningvaluesinsteadofmodifyingglobalstate,2)Ensureidempotencytohandlemultiplecallssafely,and3)Breakdowncomplexinitializationintosmaller,focusedfunctionstoenhancemodularityandm

Getting Started with Go: A Beginner's GuideGetting Started with Go: A Beginner's GuideApr 26, 2025 am 12:21 AM

Goisidealforbeginnersandsuitableforcloudandnetworkservicesduetoitssimplicity,efficiency,andconcurrencyfeatures.1)InstallGofromtheofficialwebsiteandverifywith'goversion'.2)Createandrunyourfirstprogramwith'gorunhello.go'.3)Exploreconcurrencyusinggorout

Go Concurrency Patterns: Best Practices for DevelopersGo Concurrency Patterns: Best Practices for DevelopersApr 26, 2025 am 12:20 AM

Developers should follow the following best practices: 1. Carefully manage goroutines to prevent resource leakage; 2. Use channels for synchronization, but avoid overuse; 3. Explicitly handle errors in concurrent programs; 4. Understand GOMAXPROCS to optimize performance. These practices are crucial for efficient and robust software development because they ensure effective management of resources, proper synchronization implementation, proper error handling, and performance optimization, thereby improving software efficiency and maintainability.

Go in Production: Real-World Use Cases and ExamplesGo in Production: Real-World Use Cases and ExamplesApr 26, 2025 am 12:18 AM

Goexcelsinproductionduetoitsperformanceandsimplicity,butrequirescarefulmanagementofscalability,errorhandling,andresources.1)DockerusesGoforefficientcontainermanagementthroughgoroutines.2)UberscalesmicroserviceswithGo,facingchallengesinservicemanageme

Custom Error Types in Go: Providing Detailed Error InformationCustom Error Types in Go: Providing Detailed Error InformationApr 26, 2025 am 12:09 AM

We need to customize the error type because the standard error interface provides limited information, and custom types can add more context and structured information. 1) Custom error types can contain error codes, locations, context data, etc., 2) Improve debugging efficiency and user experience, 3) But attention should be paid to its complexity and maintenance costs.

Building Scalable Systems with the Go Programming LanguageBuilding Scalable Systems with the Go Programming LanguageApr 25, 2025 am 12:19 AM

Goisidealforbuildingscalablesystemsduetoitssimplicity,efficiency,andbuilt-inconcurrencysupport.1)Go'scleansyntaxandminimalisticdesignenhanceproductivityandreduceerrors.2)Itsgoroutinesandchannelsenableefficientconcurrentprogramming,distributingworkloa

Best Practices for Using init Functions Effectively in GoBest Practices for Using init Functions Effectively in GoApr 25, 2025 am 12:18 AM

InitfunctionsinGorunautomaticallybeforemain()andareusefulforsettingupenvironmentsandinitializingvariables.Usethemforsimpletasks,avoidsideeffects,andbecautiouswithtestingandloggingtomaintaincodeclarityandtestability.

The Execution Order of init Functions in Go PackagesThe Execution Order of init Functions in Go PackagesApr 25, 2025 am 12:14 AM

Goinitializespackagesintheordertheyareimported,thenexecutesinitfunctionswithinapackageintheirdefinitionorder,andfilenamesdeterminetheorderacrossmultiplefiles.Thisprocesscanbeinfluencedbydependenciesbetweenpackages,whichmayleadtocomplexinitializations

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools