官术网_书友最值得收藏!

  • Go Systems Programming
  • Mihalis Tsoukalos
  • 340字
  • 2021-07-02 18:08:02

Printing all the values from a given column of a line

This is a very common scenario, as you often will need to get all the data from a given column of a structured text file in order to analyze it afterward. The code of readColumn.go, which prints values in the third column, will be presented in two parts.

The first part is as follows:

package main 
 
import ( 
   "fmt" 
   "strings" 
) 
 
func main() { 
   var s [3]string 
   s[0] = "1 2 3" 
   s[1] = "11 12 13 14 15 16" 
   s[2] = "-1 2 -3 -4 -5 6" 

Here, you import the required Go packages and define a string with three lines using an array with three elements.

The second part contains the following Go code:

   column := 2 
 
   for i := 0; i < len(s); i++ { 
         data := strings.Fields(s[i]) 
         if len(data) >= column { 
               fmt.Println((data[column-1])) 
         } 
   } 
} 

First, you define the column that interests you. Then, you start iterating over the strings stored in the array. This is similar to reading a text file line by line. The Go code inside the for loop splits the fields of the input line, stores them in the data array, verifies that the value from the desired column is present, and prints it on your screen. All of the hard work is done by the handy strings.Fields() function that splits a string based on whitespace characters, as defined in unicode.IsSpace(), and returns a slice of strings. Although readColumn.go does not use the regexp.Compile() function, the logic behind its implementation with the use of strings.Fields() is still based on the principles of regular expressions.

An important thing to remember is that you should never trust your data. Put simply, always verify that the data you expect to grab is there.

Executing readColumn.go will generate the following kind of output:

$ go run readColumn.go
2
12
2

Chapter 6, File Input and Output, will show an improved version of readColumn.go that you can use as a starting point in case you want to modify the rest of the examples shown.

主站蜘蛛池模板: 黄平县| 新晃| 潮安县| 绥江县| 拉萨市| 潞西市| 林州市| 兴化市| 卓资县| 鄯善县| 三河市| 从江县| 始兴县| 平阳县| 锡林郭勒盟| 庆城县| 商水县| 尉犁县| 抚顺县| 乐都县| 福州市| 资阳市| 芷江| 绥滨县| 怀远县| 小金县| 探索| 五常市| 洞头县| 淮阳县| 梅河口市| 广水市| 蒙城县| 桓台县| 武山县| 娄烦县| 都匀市| 盐源县| 马尔康县| 蒙山县| 巴塘县|