Replace specific elements in strings

5 ビュー (過去 30 日間)
Ivan Mich
Ivan Mich 2023 年 3 月 5 日
コメント済み: chrisw23 2023 年 3 月 6 日
I have a quaestion. Which command should I use in order to replace () with -.
for example I have strigs in an array like :
America (New York)
America (Manhattan)
Italy (Rome)
And I would like my output strings to be:
America - New York
America - Manhattan
Italy - Rome
Which command shouls I use? I tried strrep but no use.
Could you please help me?
  1 件のコメント
chrisw23
chrisw23 2023 年 3 月 6 日
repStr = string("America (New York)").replace(" ("," - ").replace(")","")
one of many options

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

回答 (1 件)

Stephen23
Stephen23 2023 年 3 月 5 日
編集済み: Stephen23 2023 年 3 月 5 日
Here are two approaches:
A = ["America (New York)"; "America (Manhattan)"; "Italy (Rome)"]
A = 3×1 string array
"America (New York)" "America (Manhattan)" "Italy (Rome)"
B = strrep(strrep(A,' (',' - '),')','')
B = 3×1 string array
"America - New York" "America - Manhattan" "Italy - Rome"
B = regexprep(A,'^(.+?)\s*\((.+)\)$','$1 - $2')
B = 3×1 string array
"America - New York" "America - Manhattan" "Italy - Rome"

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by