文字列の置き換えについて

下記5行1列のstring配列の中身を条件に応じて置き換えたいと思っています。
Aから始まる文字列を1、Bから始まる文字列を2、Cから始まる文字列を3に置き換えたいです。
置き換え方法についてご教授ください。
宜しくお願い致します。
A = ["A10"; "A100"; "A101"; "B20"; "C30"];

Réponses (1)

Akira Agata
Akira Agata le 10 Juin 2020

0 votes

条件の数が、ご質問の例のように3個程度であれば、以下のようにして置き換えることができます。
% (1) Straight-forward solution
idx = startsWith(A,"A");
A(idx) = "1";
idx = startsWith(A,"B");
A(idx) = "2";
idx = startsWith(A,"C");
A(idx) = "3";
別の方法として、正規表現を使った置き換えも可能です。
% (2) Another solution
A = regexprep(A,'^A.*','1');
A = regexprep(A,'^B.*','2');
A = regexprep(A,'^C.*','3');

1 commentaire

Ryuhei Funada
Ryuhei Funada le 11 Juin 2020
規則性を利用すると、
A = ["A10"; "A100"; "A101"; "B20"; "C30"];
for i=0:2
A=replace(A,char(i+65),char(i+49));
end
char(65)がA,char(66)がBです。char(49)が1、cahr(50)が2です、とインクリメントで対応できます。

Connectez-vous pour commenter.

Catégories

En savoir plus sur 文字と文字列 dans Centre d'aide et File Exchange

Produits

Version

R2018b

Community Treasure Hunt

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

Start Hunting!