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中文網其他相關文章!

goisidealforbuildingscalablesystemsduetoitssimplicity,效率和建築物內currencysupport.1)go'scleansyntaxandaxandaxandaxandMinimalisticDesignenhanceProductivityAndRedCoductivityAndRedCuceErr.2)ItSgoroutinesAndInesAndInesAndInesAndineSandChannelsEnablenableNablenableNableNablenableFifficConcurrentscorncurrentprogragrammentworking torkermenticmminging

Initfunctionsingorunautomationbeforemain()andareusefulforsettingupenvorments和InitializingVariables.usethemforsimpletasks,避免使用輔助效果,andbecautiouswithTestingTestingTestingAndLoggingTomaintAnainCodeCodeCodeClarityAndTestesto。

goinitializespackagesintheordertheordertheyimported,thenexecutesInitFunctionswithinApcageIntheirdeFinityOrder,andfilenamesdetermineTheOrderAcractacractacrosmultiplefiles.thisprocessCanbeCanbeinepessCanbeInfleccessByendercrededBydeccredByDependenciesbetenciesbetencemendencenciesbetnependendpackages,whermayleLeadtocomplexinitialitialializizesizization

CustomInterfacesingoarecrucialforwritingFlexible,可維護,andTestableCode.TheyEnableDevelostOverostOcusonBehaviorBeiroveration,增強ModularityAndRobustness.byDefiningMethodSigntulSignatulSigntulSignTypaterSignTyperesthattypesmustemmustemmustemmustemplement,InterfaceSallowForCodeRepodEreusaperia

使用接口進行模擬和測試的原因是:接口允許定義合同而不指定實現方式,使得測試更加隔離和易於維護。 1)接口的隱式實現使創建模擬對像變得簡單,這些對像在測試中可以替代真實實現。 2)使用接口可以輕鬆地在單元測試中替換服務的真實實現,降低測試複雜性和時間。 3)接口提供的靈活性使得可以為不同測試用例更改模擬行為。 4)接口有助於從一開始就設計可測試的代碼,提高代碼的模塊化和可維護性。

在Go中,init函數用於包初始化。 1)init函數在包初始化時自動調用,適用於初始化全局變量、設置連接和加載配置文件。 2)可以有多個init函數,按文件順序執行。 3)使用時需考慮執行順序、測試難度和性能影響。 4)建議減少副作用、使用依賴注入和延遲初始化以優化init函數的使用。

go'SselectStatementTreamLinesConcurrentProgrambyMultiplexingOperations.1)itallowSwaitingOnMultipleChannEloperations,執行thefirstreadyone.2)theDefirstreadyone.2)thedefefcasepreventlocksbysbysbysbysbysbythoplocktrograpraproxrograpraprocrecrecectefnoopeready.3)

contextancandwaitgroupsarecrucialingoformanaginggoroutineseflect.1)context contextsallowsAllowsAllowsAllowsAllowsAllingCancellationAndDeadLinesAcrossapibiboundaries,確保GoroutinesCanbestoppedGrace.2)WaitGroupsSynChronizeGoroutines,確保Allimizegoroutines,確保AllizeNizeGoROutines,確保AllimizeGoroutines


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

mPDF
mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

VSCode Windows 64位元 下載
微軟推出的免費、功能強大的一款IDE編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

ZendStudio 13.5.1 Mac
強大的PHP整合開發環境