Effacer les filtres
Effacer les filtres

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

75 vues (au cours des 30 derniers jours)
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',...]
  5 commentaires
harshpurohit11
harshpurohit11 le 18 Août 2018
Modifié(e) : harshpurohit11 le 18 Août 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.
Image Analyst
Image Analyst le 18 Août 2018
Yes you do. It was introduced before R2006a.

Connectez-vous pour commenter.

Réponse acceptée

Walter Roberson
Walter Roberson le 18 Août 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.
  2 commentaires
harshpurohit11
harshpurohit11 le 18 Août 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.'
Walter Roberson
Walter Roberson le 18 Août 2018
str = regexprep(names, {'[%() ]+', '_+$'}, {'_', ''});

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Characters and Strings dans Help Center et File Exchange

Produits


Version

R2014a

Community Treasure Hunt

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

Start Hunting!

Translated by