I want to remove hyphens (-
), slashes (/
) and white space () from a string
name(i)
so that I can use it as a structure field name.
This is the ugly way I am currently doing it using the function strrep
:
cell2mat(strrep(strrep(strrep(name(i), '-',''),'/',''),' ', ''))
I have also tried other variations, such as:
strrep(name(i),{'-','/'},{'',''});
strrep(name(i),['-','/'],['','']);
What is a more efficient way of doing this?
Note: I'm guessing your variable name
is a cell array of strings, in which case you will want to use {}
(i.e. content indexing) instead of ()
(i.e. cell indexing) to get the strings from it...
As with many problems in MATLAB, there are a number of different ways you can solve this...
Option 1: You could use the function REGEXPREP. The following removes hyphens, forward slashes, and whitespace:
newName = regexprep(name{i},'[-/\s]','');
The benefit here is that the \s
will match and replace all whitespace characters, which includes a normal space (ASCII code 32) as well as tabs, newlines, etc..
If you want to be safe and remove every character that is not valid in a MATLAB variable/field name, you can simplify the above to this:
newName = regexprep(name{i},'\W','');
Option 2: If you don't need to worry about removing anything other than the 3 characters you listed, you could use the function ISMEMBER like so:
newName = name{i};
newName(ismember(newName,'-/ ')) = [];
Option 3: If you want to just keep everything that is an alphanumeric character and dump the rest (hyphens, whitespace, underscores, etc.), you could use the function ISSTRPROP:
newName = name{i};
newName = newName(isstrprop(newName,'alphanum'));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With