To remove leading and trailing spaces from the string, you can use the DEBLANK function:
str = ' Hello, World! '
str = deblank(str)
str_flipped = str(end:-1:1)
str_flipped = deblank(str_flipped)
str = str_flipped(end:-1:1)
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.
Best Answer