How can I replicate the strtrim function?

I am trying to replicate the strtrim function, but I cannot seem the figure out how to get it to work properly. When I run my code, it takes every single space (or tab) out of the string. I cannot figure out how to make it take only the leading and trailing spaces out. I know the strtrim function can do that, but I am trying to replicate that function. A detailed explanation of the solution would be much appreciated. Thank you all.
a = ' some words with spaces ';
k=1;
while k <= length(a)
if a(k) == char(32)
a(k) = '';
k = k+1;
elseif a(k) == char(9)
a(k) = '';
else
k = k+1;
end
end

Antworten (2)

Star Strider
Star Strider am 3 Mär. 2016
Bearbeitet: Star Strider am 3 Mär. 2016

0 Stimmen

You can do it with a relatively simple regexp call:
a = ' some words with spaces ';
[s, e] = regexp(a, '\S*');
Result = a(s(1):e(end))
Result =
some words with spaces

3 Kommentare

What if I were to do an sprintf call with a tab at the front, and I want the tab to stay?
if true
a = sprintf('\tsome words with spaces ');
%Desired_Outcome = sprintf('\tsome words with spaces');
end
Star Strider
Star Strider am 4 Mär. 2016
It’s probably possible to do that with regexp, but it’s eluding me. I can get regexp to do some of it but not all of it at once.
Result = regexprep(a, {'^ +', '\s+$'}, {'', ''})

Melden Sie sich an, um zu kommentieren.

Walter Roberson
Walter Roberson am 3 Mär. 2016

0 Stimmen

Hint: when you are removing something from a matrix in a loop, always start from the end and move to the beginning. Think of it like Tetris and "falling down" into vacated slots...

Kategorien

Mehr zu Characters and Strings finden Sie in Hilfe-Center und File Exchange

Produkte

Gefragt:

am 3 Mär. 2016

Kommentiert:

am 4 Mär. 2016

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by