Replace specific elements in strings

조회 수: 6 (최근 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 CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by