Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert underscores to spaces in Matlab string?

So say I have a string with some underscores like hi_there.

Is there a way to auto-convert that string into "hi there"?

(the original string, by the way, is a variable name that I'm converting into a plot title).

like image 686
InquilineKea Avatar asked Nov 06 '25 00:11

InquilineKea


1 Answers

Surprising that no-one has yet mentioned strrep:

>> strrep('string_with_underscores', '_', ' ')
ans =
string with underscores

which should be the official way to do a simple string replacements. For such a simple case, regexprep is overkill: yes, they are Swiss-knifes that can do everything possible, but they come with a long manual. String indexing shown by AndreasH only works for replacing single characters, it cannot do this:

>> s = 'string*-*with*-*funny*-*separators';
>> strrep(s, '*-*', ' ')
ans =
string with funny separators

>> s(s=='*-*') = ' '
Error using  == 
Matrix dimensions must agree.

As a bonus, it also works for cell-arrays with strings:

>> strrep({'This_is_a','cell_array_with','strings_with','underscores'},'_',' ')
ans = 
    'This is a'    'cell array with'    'strings with'    'underscores'
like image 192
Bas Swinckels Avatar answered Nov 07 '25 15:11

Bas Swinckels