2012-01-18 263 views
1

說我有這樣一個變量的字符串在MATLAB如下:添加一個字符串到每一行,在MATLAB字符串

this is the first line 
this is the second line 
this is the third line 

我想在每個月初加一個固定的字符串線。例如:

add_substring(input_string, 'add_this. ') 

將輸出:

add_this. this is the first line 
add_this. this is the second line 
add_this. this is the third line 

我知道我可以通過輸入字符串循環做到這一點,但我要尋找一個更緊湊的(希望矢量)的方式來做到這一點,也許使用MATLAB內建的一個例如arrayfunaccumarray

回答

6

strcat功能就是你要找的。它矢量化了字符串的連接。

strs = { 
    'this is the first line' 
    'this is the second line' 
    'this is the third line' 
    } 
strcat({'add_this. '}, strs) 

隨着strcat的,你需要把'add_this. '在細胞({}),以保護其免受其剝去其尾隨的空白,這是字符輸入的strcat的正常行爲。

+0

輸入字符串在技術上不是一個單元格數組,而是一個char字符串,但是我可以使用'[input_string,〜] = regexp(input_string,'\ n','split')將其轉換爲一個'' – 2012-01-18 16:07:39

+0

'Strcat'工作也在'char'輸入上。但是你仍然需要做這樣的分割,因爲多個字符串作爲'char'被存儲在一個2-d char矩陣中的單獨行;看起來像你的輸入是一個單一的多行字符串。 – 2012-01-18 16:26:56

0

假設你的字符串存儲在一個單元格數組中,那麼cellfun將會做你想做的事情,例如,

s = {'this is the first line', 'this is the second line', 'this is the third line'}; 
prefix = 'add_this. '; 
res = cellfun(@(str) strcat(prefix, str), s, 'UniformOutput', false); 
+0

檢查'res'輸出;前綴正在被剝離。 – 2012-01-18 15:35:26

相關問題