soldin
1
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?
rdeits
2
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()
julia> str1 = ["abc", "def", "ghi"]
3-element Vector{String}:
"abc"
"def"
"ghi"
julia> join(str1)
"abcdefghi"
5 Likes
soldin
3
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
jling
4
2 Likes
soldin
5
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
Adding to this, join
lets you specify a delimiter:
julia> join(("a","b","c"), "; ")
"a; b; c"
1 Like
soldin
9
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