假设我有一个带下划线的字符串,比如hi_there。
有没有一种自动将该字符串转换为“hi there”的方法?
(顺便说一句,原始字符串是变量名,我正在将其转换为绘图标题。)
令人惊讶的是还没有人提到strrep
:
>> strrep('string_with_underscores', '_', ' ')
ans =
string with underscores
regexprep
太过于臃肿了:是的,它能够胜任一切任务,但使用手册非常冗长。AndreasH 提供的字符串索引仅适用于替换单个字符,无法做到这一点:>> s = 'string*-*with*-*funny*-*separators';
>> strrep(s, '*-*', ' ')
ans =
string with funny separators
>> s(s=='*-*') = ' '
Error using ==
Matrix dimensions must agree.
>> strrep({'This_is_a','cell_array_with','strings_with','underscores'},'_',' ')
ans =
'This is a' 'cell array with' 'strings with' 'underscores'
尝试使用以下 Matlab 代码处理字符串变量 's'
s(s=='_') = ' ';
如果你需要处理更加复杂的事情,比如替换多个不同长度的字符串,s(s == '_') = ' '
将会是一个巨大的痛苦。如果你需要进行更复杂的替换,请考虑使用 regexprep
:
>> regexprep({'hi_there', 'hey_there'}, '_', ' ')
ans =
'hi there' 'hey there'
话虽如此,在您的情况下,@AndreasH.的解决方案是最合适的,使用regexprep
会过度。
更有趣的问题是为什么您要将变量作为字符串传递?
regexprep()可能是你正在寻找的内容,它通常是一个方便的函数。
regexprep('hi_there','_',' ')
将第一个参数字符串取出,并用第三个参数替换第二个参数的所有实例。在此示例中,它将所有下划线替换为一个空格。
text = 'variable_name';
text(text=='_') = ' '; //replace all occurrences of underscore with whitespace
=> text = variable name
我知道这个问题已经有答案了,但是在我的情况下,我正在寻找一种方法来更正图表标题,以便我可以包含一个文件名(其中可能包含下划线)。因此,我希望将它们打印出来时,下划线不会显示为下标。所以,利用上面提供的这些很棒的信息,我使用了转义字符代替了空格。
For example:
% Have the user select a file:
[infile inpath]=uigetfile('*.txt','Get some text file');
figure
% this is a problem for filenames with underscores
title(infile)
% this correctly displays filenames with underscores
title(strrep(infile,'_','\_'))