Replace specific elements in strings

6 Ansichten (letzte 30 Tage)
Ivan Mich
Ivan Mich am 5 Mär. 2023
Kommentiert: chrisw23 am 6 Mär. 2023
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 Kommentar
chrisw23
chrisw23 am 6 Mär. 2023
repStr = string("America (New York)").replace(" ("," - ").replace(")","")
one of many options

Melden Sie sich an, um zu kommentieren.

Antworten (1)

Stephen23
Stephen23 am 5 Mär. 2023
Bearbeitet: Stephen23 am 5 Mär. 2023
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"

Kategorien

Mehr zu Characters and Strings finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by