Andrew Plummer
Andrew Plummer

Reputation: 23

How Can I Remove Non-Breaking Leading Whitespace in Matlab?

Say I have a string variable, " Fruit".

Usually, I use strtrim() to remove the leading whitespace. Therefore, " Fruit" becomes "Fruit".

However, if the leading whitespace is non-breaking, i.e. char(160), then strtrim, as well as its cousins - deblank and strtok - cannot remove this leading whitespace.

I also tried to use a for loop to replace " Fruit" with "Fruit" but the for loop doesn't seem to recognize " Fruit", which indicates I'm identifying it incorrectly.

Here is my for loop

for i=1:height(T)
    if T.Foods(i) == " Fruit"
        T.Foods(i) = "Fruit"
    end
end

What is one way I can remove this leading, non-breaking whitespace, or at least, replace it with a variable without whitespaces?

Upvotes: 1

Views: 859

Answers (1)

Wolfie
Wolfie

Reputation: 30047

You can use regexprep to match the regular expression \s (any whitespace character) and replace with ''

>> str = [char(160), 'fru', char(160), 'it', char(160), char(160)]
str =
    ' fru it  '

>> regexprep( str, '\s', '' )
ans =
    'fruit'

As noted in the comments, to target only leading whitespace you would use

regexprep( str, '^\s+', '' )

Upvotes: 1

Related Questions