Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Julia - Trim string whitespace and check length

Tags:

string

julia

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 
like image 323
nalyd88 Avatar asked Dec 12 '16 17:12

nalyd88


2 Answers

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

like image 170
isebarn Avatar answered Sep 28 '22 09:09

isebarn


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/)

like image 37
Alexander Morley Avatar answered Sep 28 '22 10:09

Alexander Morley