フィルターのクリア

for loop multiple string replace

7 ビュー (過去 30 日間)
Siti Safwana Abd Razak
Siti Safwana Abd Razak 2022 年 12 月 30 日
hi all,
i want to replace some old string with new one. i can do in multiple strrep as below:
newChr = strrep(strrep(strrep(strrep(f, 'old', 'wana'), ...
'old1', 'wana1'), ...
'old2','wana2'), ...
'old3','wana3')
but it not convenient to replace 300++ new word. i try to do for loop as below, but dont have any idea to do it. Below my for loop code, anyone can helpme to automate this thing? for now, im still replace using the above methods. thanks
numLines = length(TestInstanceold);
for k = 1:numLines
filename = 'a.txt';
fid = fopen(filename,'r');
f=fread(fid,'*char')';
fclose(fid);
f= strrep(f, TestInstanceold(k,1), TestInstanceold(k,1))
end

採用された回答

Stephen23
Stephen23 2022 年 12 月 30 日
編集済み: Stephen23 2022 年 12 月 30 日
MATLAB is designed to work neatly and efficiently with arrays. Rather than doing things one-at-a-time like that, you should be using arrays. For example:
A = "title: the cat in the hat";
old = [ "the", "cat", "in", "hat"];
new = ["seven","brides","for","brothers"];
Method one: REPLACE():
Z = replace(A,old,new)
Z = "title: seven brides for seven brothers"
Method two: REGEXPREP():
B = regexprep(A,old,new)
B = "title: seven brides for seven brothers"
Method three: STRREP() in a loop:
C = A;
for k = 1:numel(old)
C = strrep(C,old{k},new{k});
end
display(C)
C = "title: seven brides for seven brothers"
  1 件のコメント
Siti Safwana Abd Razak
Siti Safwana Abd Razak 2022 年 12 月 30 日
thanks steven! its works

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

製品


リリース

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by