2013-09-01 80 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','_',' ') 

將採用第一個參數字符串,並將第二個參數的實例替換爲第三個參數。在這種情況下,它將用空格替換所有下劃線。

相關問題