How to split a string in Julia?

Viewed 4401

I have the following line read in from my text file: "1200, 1200" and I want to split the string on the ", " such that I can access the raw numbers. How can I do that in Julia?

2 Answers

Check out this comprehensive article on Splitting Strings in Julia.

Julia has a simple split function which takes in two arguments. The first is the string you want to split and the second is the delimiter (the thing you want to split on/by). Both parameters that are passed to the split function should be strings.

In this example:

data = readlines("numbers.txt") # Returns a one dimensional array of strings. 
xmin, ymin = split(data[1], ", ") # data[1] indexs into that 1-D array to get the string

we read in all of the data from a text file which is just simple "1200, 1400".

We can then use the split function to separate the two numbers into "xmin" and "ymin". In this example, after the code is run, "xmin" will be equal to 1200 and "ymin" will be equal to 1400.

Read more about the split function in the Julia docs.

To start, you may want to check out this article on Splitting Strings in Julia.

In scenarios like this (simple text file parsing) use DelimetedFiles. It is usually most robust and most straightforward to use.

Consider the following file:

open("file.txt","w") do f
    println(f, "1200, 2000, 3000\n1300, 4000, 5000")
end

And now let us read it

julia> using DelimitedFiles

julia> readdlm("file.txt", ',',Int)
2×3 Array{Int64,2}:
 1200  2000  3000
 1300  4000  5000

There are many parameters available to control the process but the beautiful thing is that their default values make the parsing process smart and straight-forward.

Related