Azzera filtri
Azzera filtri

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

75 visualizzazioni (ultimi 30 giorni)
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 Commenti
harshpurohit11
harshpurohit11 il 18 Ago 2018
Modificato: harshpurohit11 il 18 Ago 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.

Accedi per commentare.

Risposta accettata

Walter Roberson
Walter Roberson il 18 Ago 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 Commenti
harshpurohit11
harshpurohit11 il 18 Ago 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.'

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Characters and Strings in Help Center e File Exchange

Prodotti


Release

R2014a

Community Treasure Hunt

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

Start Hunting!

Translated by