How to declare a string array for the purpose of concatenation

Hi all,
I have the following code of converting a string array into a char array (MATLAB’s parlance)

This works

str1 = ["abc", "def", "ghi"]

function str_join(str2)
str=str2[1]

for i=2:1:length(str2)
    
    str = string(str,str2[i]) 
    
end

    return str

end 

str3 = str_join(str1)
display(str3)

Output: “abcdefghi”

This doesn’t work

str1 = ["abc", "def", "ghi"]

function str_join(str2)
str = Array{String}(undef,1)

str[1]=str2[1]

for i=2:1:length(str2)
    
    str = string(str,str2[i]) 
    
end

    return str

end 

str3 = str_join(str1)
display(str3)

Output: “["abc"]defghi”

Is there any way to get rid of this residue of undef?

The undef isn’t really relevant here. The point is that you’re doing string(str, ...), where str is an array of strings (initially with one element).

string(["abc"]) gives ["abc"], which just isn’t what you want here.

If you want the easy answer, the way to join strings is…join() :slightly_smiling_face:

julia> str1 = ["abc", "def", "ghi"]
3-element Vector{String}:
 "abc"
 "def"
 "ghi"

julia> join(str1)
"abcdefghi"
5 Likes

Thank you rdeits for your input. I was used to this MATLAB’s way

str1 = ["abc", "def", "ghi"];
str2 = [];

for i=1:1:length(str1)
    
    str2 = [str2 str1(i)] ;
    
end

https://docs.julialang.org/en/v1/manual/strings/#Common-Operations

might want to give the short and sweet Manual a read.

2 Likes

Thank you jling for the link. Now going through it more carefully!

FWIW, prod(str1) produces here the same result as join(str1)

1 Like

Thank you Rafael.

Adding to this, join lets you specify a delimiter:

julia> join(("a","b","c"), "; ")
"a; b; c" 
1 Like

Interesting. Thank you Gustaphe.

Another cool use of join is you don’t need to create the string if you’re printing it to a file or other io:

julia> join(stdout, ("a", "b", "c"), "; ")
a; b; c
julia> open("file.txt", "w") do f
           join(f, ("a", "b", "c"), "; ")
       end
3 Likes