Clear Filters
Clear Filters

How to remove spaces and special characters from elements of a char array

67 views (last 30 days)
char array names = ['time (s)', 'speed (%)',....]
I want to save the char array such that () and % characters are removed, meaning names = ['time_s', 'accel_pedal',...]
harshpurohit11 on 18 Aug 2018
Edited: harshpurohit11 on 18 Aug 2018
I have a 640 elements long char array with three set of characters %, (, ) and spaces which I want to replace with '_'. I am using matlab 2014a which does not have the strrep function in it.

Sign in to comment.

Accepted Answer

Walter Roberson
Walter Roberson on 18 Aug 2018
str = regexp( names, '[%() ]', '_');
But more likely you want
str = regexp(names, {'[%() ]+', '_+$'}, {'_', ''});
But it is a bit confusing what you are asking, especially since you are using a version before the string() data type. The notation
['time (s)', 'speed (%)',....]
would create a single character vector that started with
'time (s)speed (%)'
and once that was constructed there would be no way of knowing where the original breaks between the elements had been -- not unless we could count on each entry ending in ')' . If we can count on that, then would the desired output be
'time_s speed'
I am uncertain as to your actual input is something like,
names = ['time (s) ';
'speed (%)']
so a char array with 640 rows and blank padding to make the rows all the same size? If so then preserving the char array nature would be slightly awkward, and would raise the question of whether the new char array should be the same size as the input or should instead only have as many columns as needed to represent the widest entry excluding trailing blanks.
Or perhaps what you have is a cell array of character vectors,
names = {'time (s)', 'speed (%)',....};
If so then the two regexp() I posted above will work.
harshpurohit11 on 18 Aug 2018
Thanks a lot for the answers walter. And you are right names = {'time (s)'; 'speed (%)';...}. However when i tried using two regexp() i got an error saying 'The 'STRING' input must be a one-dimensional array of char or cell arrays of strings.'

Sign in to comment.

More Answers (0)


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




Community Treasure Hunt

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

Start Hunting!