How do I remove leading and trailing spaces from a string?

14 views (last 30 days)
How do I remove leading and trailing spaces from a string?
I have a string with many spaces at the beginning and the end. I want to remove these spaces without removing internal spacing (using STRREP(str,' ','') ). Is there a way to trim the string?

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 13 Dec 2021
Edited: MathWorks Support Team on 13 Dec 2021
To remove leading and trailing spaces from the string, you can use the DEBLANK function:
str = ' Hello, World! '
str = deblank(str) %remove trailing spaces
str_flipped = str(end:-1:1) %flip the string
str_flipped = deblank(str_flipped) %remove trailing spaces of the flipped string
str = str_flipped(end:-1:1) %flip the string back
The resulting string does not contain any leading or trailing spaces:
str
str = 'Hello, World!'
To remove leading spaces from the string, you can also use the STRTOK function, which finds the first token in the string. (A token is the first set of characters that is encountered before a delimiter. In the following example, it is white space.) Leading delimiters are ignored. For example:
str = ' Hello '
str_new = strtok(str)
The first token of the string 'str' without any leading spaces is found:
str_new
str_new = 'Hello'
If you have a string containing more than one token and want to remove leading spaces from the string, you can use STRTOK in the following format:
[token,rem] = strtok(str)
where 'str' is the input string, 'token' is the first token, and 'rem' is the remainder. Then combine the outputs 'token' and 'rem'.
For example:
str = ' Hello, World!'
[t,r] = strtok(str)
str_new = [t r]
Here is the output:
t = 'Hello,'
r = ' World!'
str_new = 'Hello, World!'
For more information on these functions, type 'help function_name' at the MATLAB command prompt. If you have installed the documentation, type 'doc function_name' to see the documentation for these functions. If you do not have the documentation installed, you can find it here:
Simply type the function name in the search box.

More Answers (0)

Categories

Find more on Characters and Strings in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!