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

18 ビュー (過去 30 日間)
MathWorks Support Team
MathWorks Support Team 2009 年 6 月 27 日
編集済み: MathWorks Support Team 2021 年 12 月 13 日
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 日
編集済み: 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 Center および File ExchangeCharacters and Strings についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by