String 在Matlab字符串中将下划线转换为空格?
假设我有一个带下划线的字符串,比如hi_ 有没有办法将该字符串自动转换为“hi there”String 在Matlab字符串中将下划线转换为空格?,string,matlab,replace,String,Matlab,Replace,假设我有一个带下划线的字符串,比如hi_ 有没有办法将该字符串自动转换为“hi there” (顺便说一下,原始字符串是一个变量名,我正在将其转换为绘图标题)。请尝试使用此Matlab代码获取字符串变量's' s(s=='_') = ' '; 在Matlab中,字符串是向量,因此可以使用标准运算符(例如,用空格替换u))执行简单的字符串操作 text = 'variable_name'; text(text=='_') = ' '; //replace all occurrences of u
(顺便说一下,原始字符串是一个变量名,我正在将其转换为绘图标题)。请尝试使用此Matlab代码获取字符串变量's'
s(s=='_') = ' ';
在Matlab中,字符串是向量,因此可以使用标准运算符(例如,用空格替换u))执行简单的字符串操作
text = 'variable_name';
text(text=='_') = ' '; //replace all occurrences of underscore with whitespace
=> text = variable name
如果要做更复杂的事情,比如替换多个可变长度字符串
s(s==''.''='
将是一个巨大的痛苦。如果您的替代品需要更复杂,请考虑使用<代码> ReXEXPRP < /代码>:
>> regexprep({'hi_there', 'hey_there'}, '_', ' ')
ans =
'hi there' 'hey there'
>> strrep('string_with_underscores', '_', ' ')
ans =
string with underscores
也就是说,在您的情况下,@AndreasH.的解决方案是最合适的,而regexprep
则是矫枉过正
一个更有趣的问题是,为什么要将变量作为字符串传递?regexprep()可能就是您要寻找的,并且通常是一个方便的函数
regexprep('hi_there','_',' ')
将获取第一个参数字符串,并用第三个参数替换第二个参数的实例。在本例中,它用空格替换所有下划线。令人惊讶的是,还没有人提到strep:
>> regexprep({'hi_there', 'hey_there'}, '_', ' ')
ans =
'hi there' 'hey there'
>> 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'
我知道这已经得到了回答,但是,在我的例子中,我正在寻找一种方法来更正情节标题,以便可以包含一个文件名(可以有下划线)。所以,我想用下划线打印它们,而不是用下标显示。因此,使用上面的这些信息,而不是空格,我在替换中转义了下标
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,'_','\_'))
这在Matlab中不起作用(可能是倍频程),因为双引号很糟糕。是的,我使用八度:)
strep
也比regexprep
快得多。您好,请确保问题的答案实际上是对问题的回答。