nalyd88
nalyd88

Reputation: 5128

Julia - Trim string whitespace and check length

I'm new to Julia and I was wondering if there were any built in functions for trimming string whitespace? I also want to check the length of the string which I know I can do with length(s) == 0, but I wondered if there where other built in functions? Thanks!

I'm basically trying to find the Julia equivalent to the following MATLAB code:

line = strtrim(line);        
if isempty(line), continue; end % Skip empty lines 

Upvotes: 17

Views: 15756

Answers (2)

isebarn
isebarn

Reputation: 3940

For the start/end of a string you have

lstrip(string)
rstrip(string)

if you need to take everything out I recommend you use something like

a = "a b c d e f"
join(map(x -> isspace(a[x]) ? "" : a[x], 1:length(a)))

because sometimes you can get strings that include some weird whitespaces that wont match " " or ' ' as is shown here

Edit

filter(x -> !isspace(x), a)

as suggested by Fengyang Wang, is even better

Upvotes: 15

Alexander Morley
Alexander Morley

Reputation: 4181

lstrip for leading whitespace, rstrip for trailing whitespace, stripfor both.

There is an isempty function for julia as well:

isempty("")
>> true

Perhaps you should check out the Julia docs for other string-related functions (https://docs.julialang.org/en/stable/ & https://docs.julialang.org/en/stable/manual/strings/)

Upvotes: 18

Related Questions