所以說我有一個像hi_there一樣下劃線的字符串。將下劃線轉換爲Matlab字符串中的空格嗎?
有沒有辦法將該字符串自動轉換爲「hi there」?
(順便說一下,原始字符串是一個變量名稱,我將其轉換爲繪圖標題)。
所以說我有一個像hi_there一樣下劃線的字符串。將下劃線轉換爲Matlab字符串中的空格嗎?
有沒有辦法將該字符串自動轉換爲「hi there」?
(順便說一下,原始字符串是一個變量名稱,我將其轉換爲繪圖標題)。
讓人意外的是,沒有人還沒有提到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'
嘗試使用一個字符串變量「s」的
s(s=='_') = ' ';
在Matlab中串矢量,所以執行簡單的字符串操作這個Matlab代碼可以使用標準操作符例如可以實現用空格替換_。
text = 'variable_name';
text(text=='_') = ' '; //replace all occurrences of underscore with whitespace
=> text = variable name
這並不在Matlab工作(可能是八度)因爲雙引號 –
我的不好。是的,我使用Octave :) – GordyD
如果你做任何事情比較複雜,說做了更換多個可變長度的字符串,
s(s == '_') = ' '
將是一個巨大的痛苦。如果您的更換需求日益變得更加複雜,可以考慮使用regexprep
:
>> regexprep({'hi_there', 'hey_there'}, '_', ' ')
ans =
'hi there' 'hey there'
話雖這麼說,你的情況@ AndreasH的解決方案是最合適,最regexprep
是矯枉過正。
一個更有趣的問題是爲什麼你將變量作爲字符串傳遞?
regexprep()可能是您正在查找的內容,並且通常是一個方便的功能。
regexprep('hi_there','_',' ')
將採用第一個參數字符串,並將第二個參數的實例替換爲第三個參數。在這種情況下,它將用空格替換所有下劃線。
'strrep'比'regexprep'快得多。 – horchler