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

18 次查看(过去 30 天)
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?

采纳的回答

MathWorks Support Team
编辑:MathWorks Support Team 2021-12-13
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.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Characters and Strings 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by