Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return last item of strings.Split() slice in Golang

Tags:

I am splitting file names in Go to get at the file extension (e.g. import ("strings") ; strings.Split("example.txt", ".")). For this reason, I would like to return the last item in the slice returned by the split, i.e.

for strings.Split("ex.txt", "."), I want txt

This question suggests that doing

strings.Split("ex.txt", ".")[len(strings.Split("ex.txt", ".")) - 1] 

is the only way to get at it. That is, there is no -1 as in Python. This seems very wasteful to me, as I feel we are doing the same splitting operation twice.

  • Is there no better command for getting the last item of a slice in Go?
  • If no, would the best approach be to write the result of Split into a variable, or just do the above?

Thank you!

like image 943
patrick Avatar asked May 12 '18 22:05

patrick


People also ask

How do you get the last element of slice in Go?

len function is used to fetch last element of Slice and remove last element from Slice.

How do you find the last value of a split string?

To split a string and get the last element of the array, call the split() method on the string, passing it the separator as a parameter, and then call the pop() method on the array, e.g. str. split(','). pop() . The pop() method will return the last element from the split string array.

How do you get the last word of a string in Golang?

LastIndex() is a built-in function of strings package in Golang. This function is used to check the index of the last occurrence of a specified substring in a given original string. If the substring is found in the given string, then it returns its index position, starting from 0; otherwise it returns "-1".


2 Answers

strings.LastIndex makes this quite neat:

s := "Hello,Stack,Overflow" last := s[strings.LastIndex(s, ",")+1:] fmt.Println(last) 

returns "Overflow". If the search string isn't found it returns the whole string, which is logical.

Playground here

like image 138
Jon Egerton Avatar answered Sep 27 '22 21:09

Jon Egerton


You should assign the results of the split to a variable, instead of calling it twice.

ss := strings.Split(msg, ".") s := ss[len(ss)-1] 

(Notice that this allows (or maybe forces) you to deal with the case where ss is empty or something else unexpected explicitly, before indexing it.)

If you're doing this over and over again, and it offends you having to use two lines (or two lines plus error handling) instead of one, you can abstract it into a function easily:

func lastString(ss []string) string {     return ss[len(ss)-1] }  s1 := lastString(strings.Split("example.txt", ".")) s2 := lastString(strings.Split("example.jpg", ".")) 

After all, passing the result of a function as an argument has essentially the same effect as binding it to a variable.

like image 30
abarnert Avatar answered Sep 27 '22 20:09

abarnert