How to replace a single word in a string with multiple row string?

Hello,
I am trying to replace a single word/token in a string variable with a string containing multiple rows of words. I get the following error using regexprep function :
Error using regexprep The 'REPLACE' input must be a one-dimensional array of char or cell arrays of strings.
I tried using strrep function as well. I get the following error for it :
Error using strrep Input strings must have one row.
A = strrep(B,'Keyword',C);
A = regexprep(B,'Keyword',C);
I am trying to replace Keyword in String B with C. C has multiple rows of words in it.
I searched the forum for similar questions. Did not find any.
How do i prevent this error? Please help.

1 件のコメント

Guillaume
Guillaume 2014 年 12 月 10 日
編集済み: Guillaume 2014 年 12 月 10 日
What are you expecting as an output? Several strings, each with one of your replacement word?
Also is your C a 2D char array or a cell array of strings?
It would be best if you gave an example of values for your A, B and C

サインインしてコメントする。

 採用された回答

Guillaume
Guillaume 2014 年 12 月 10 日

0 投票

This is possibly what you want:
B = 'Some string with a Keyword in it';
C = {'foo', 'bar', 'baz'};
A = cellfun(@(rep) strrep(B, 'Keyword', rep), C, 'UniformOutput', false)
If your C is a 2D char array and you also want a 2D char array as an output
B = 'Some string with a Keyword in it';
C = ['foo';'bar';'baz'];
A = cell2mat(cellfun(@(rep) strrep(B, 'Keyword', rep), num2cell(C, 2), 'UniformOutput', false))

2 件のコメント

Math
Math 2014 年 12 月 10 日
編集済み: Math 2014 年 12 月 10 日
Hello Guilaume,
Yes C is a 2D char array and i also want a 2D char array as an output.
However, I want the output as:
Some string with a foo bar baz in it.
B can also a 2D char array in my case. I was able to replace Keyword in B with single token. But i am not able to replace Keyword with 2D char array.
Guillaume
Guillaume 2014 年 12 月 10 日
It is much simpler to work with cell arrays of strings than 2D char arrays. Most string functions will happily work on multiple strings as long as they're in a cell array. A cell array has the added advantage that your strings don't have to be all the same length.
Use num2cell to convert a 2D array to cell, and cell2mat to convert back.
Anyway
B=['A string with Keyword'; 'Another Keyword abcde'];
C=['foo';'bar';'baz'];
Bascell = num2cell(B, 2);
Cascell = num2cell(C, 2);
Aascell = strrep(Bascell, 'Keyword', strjoin(Cascell));
A = cell2mat(Aascell)

サインインしてコメントする。

その他の回答 (1 件)

Math
Math 2014 年 12 月 10 日
編集済み: Math 2014 年 12 月 10 日

0 投票

Some string with foobarbaz in it. as output is also acceptable. I thought of concatenating C. But it's size is not fixed for different cases.

カテゴリ

ヘルプ センター および File ExchangeCharacters and Strings についてさらに検索

質問済み:

2014 年 12 月 10 日

コメント済み:

2014 年 12 月 10 日

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by