首頁  >  文章  >  後端開發  >  訪問切片中包含的字串

訪問切片中包含的字串

王林
王林轉載
2024-02-10 20:00:191156瀏覽

訪問切片中包含的字串

php小編小新在這裡為大家介紹如何存取切片中包含的字串。在php中,切片是指從一個字串中截取一部分字元的操作。透過存取切片中的字串,我們可以取得所需的資料或進行其他操作。在使用切片時,我們需要指定起始位置和結束位置,即可取得對應的字串。掌握切片的使用方法,將為我們的開發工作帶來很大的便利。接下來,讓我們一起來詳細了解如何實現存取切片中包含的字串的操作吧!

問題內容

我正在做一些編碼練習,以便更好地理解 go。給定的練習指示我創建一個接受使用者輸入的程序,如下所示:

  • 第一行指定將提供多少個字串作為單獨行的輸入
  • 接下來的 n 行每行都是單一字串

我要輸出與每個字串的偶數和奇數索引相對應的字符,並用空格分隔,並且每個字串位於單獨的行上。

輸入範例:

2
foo_bar
fizz_buzz

應該輸出:

fobr o_a
fz_uz izbz

但是在我的程式中存取字串切片會傳回一個空字串:

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

解決方法

因為當您make strings 切片時,您正在建立一個容量和長度n的切片。因此,當您附加到它時,您就增加了切片的長度:

更改這段程式碼:

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

到:

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

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

你應該表現得很好。

以上是訪問切片中包含的字串的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:stackoverflow.com。如有侵權,請聯絡admin@php.cn刪除