2013-09-01 84 views

回答

5

让人意外的是,没有人还没有提到strrep

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

这应该是official way做一个简单的字符串替换。对于这样一个简单的例子,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' 
+0

'strrep'比'regexprep'快得多。 – horchler

5

尝试使用一个字符串变量“s”的

s(s=='_') = ' '; 
1

在Matlab中串矢量,所以执行简单的字符串操作这个Matlab代码可以使用标准操作符例如可以实现用空格替换_。

text = 'variable_name'; 
text(text=='_') = ' '; //replace all occurrences of underscore with whitespace 
=> text = variable name 
+1

这并不在Matlab工作(可能是八度)因为双引号 –

+0

我的不好。是的,我使用Octave :) – GordyD

2

如果你做任何事情比较复杂,说做了更换多个可变长度的字符串,

s(s == '_') = ' '将是一个巨大的痛苦。如果您的更换需求日益变得更加复杂,可以考虑使用regexprep

>> regexprep({'hi_there', 'hey_there'}, '_', ' ') 
ans = 
    'hi there' 'hey there' 

话虽这么说,你的情况@ AndreasH的解决方案是最合适,最regexprep是矫枉过正。

一个更有趣的问题是为什么你将变量作为字符串传递?

2

regexprep()可能是您正在查找的内容,并且通常是一个方便的功能。

regexprep('hi_there','_',' ') 

将采用第一个参数字符串,并将第二个参数的实例替换为第三个参数。在这种情况下,它将用空格替换所有下划线。

相关问题