How to efficiently concatenate a string array and string in golang

I have a string of strings and [] strings in golang that I need to concatenate. But for some reason, I get a lot of gaps along the way that I need to get rid of.

Here is the code

tests := strings.TrimSpace(s[0]) dep_string := make ([]string, len(tests) + len(sfinal)) dep_string = append (dep_string,tests) for _,v := range sfinal { dep_string = append(dep_string,v) } fmt.Println("dep_String is ",dep_string) Input: s[0] = "filename" sfinal = [test test1] expected output [filename test test1] actual output [ filename test test1] 

This is really strange; even after using TrimSpace, I can’t get rid of the extra space. Is there an effective way to concatenate them?

+7
go
source share
5 answers

Space due to all empty elements in dep_string. When you use the make function, it creates a slice with the specified length and capacity, filled with a bunch of nothing. Then, when you use the append, it sees that the slice has reached its maximum capacity, expands the slice, and then adds your elements after nothing. The solution is to make a slice with the ability to hold all your elements, but with an initial length of zero:

 dep_string := make ([]string, 0, len(tests) + len(sfinal)) 

string.TrimSpace is not needed. You can read more at http://blog.golang.org/slices

+7
source share

Bill DeRose and Saposhiente are correct about how slices work.

As for a simpler way to solve your problem, you can also do ( play ):

 fmt.Println("join is",strings.Join(append(s[:1],sfinal...)," ")) 
+4
source share

When you do the assignment dep_string := make ([]string, len(tests) + len(sfinal)) , Go zeros allocates the allocated memory, so dep_string and then len(tests) + len(sfinal) empty lines in front of it. As already written, you add the end of the fragment after all these nullified lines.

Run this one to see where these spaces appear in your code. You can fix it by making instead a slice of length 0 and capacity len(tests) + len(sfinal) . Then you can combine them using strings.Join .

0
source share

Here is a simple and effective solution to your problem.

 package main import "fmt" func main() { s := make([]string, 1, 4) s[0] = "filename" sfinal := []string{"test", "test1"} dep_string := append(s[:1], sfinal...) fmt.Println("dep_String is ", dep_string) } 

Output:

 dep_String is [filename test test1] 
0
source share

When you execute the assignment dep_string := make ([]string, len(tests) + len(sfinal)) , it selects the lines len(tests) + len(sfinal) null, in your case it is 10 zero lines, so when you do the assignment fmt.Println("dep_String is ",dep_string) , it will print 10 zero lines, because fmt.Println(slice of string) will add a space between the two elements, so it will print 9 blanks, so after adding it will be [ filename test test1] after adding, spaces are spaces between 10 zero lines.

0
source share

All Articles