How can I replace a certain pattern in a string?

조회 수: 1 (최근 30일)
Tian
Tian 2023년 3월 16일
댓글: Voss 2023년 3월 16일
Hi! I'm trying to replace a certain pattern in a string using strrep. The original string is like 'abbabba', and I want to replace all 'abba' into 'aaaa'. The expected result is 'aaaaaaa' (7 'a's). I tried the following command:
strrep('abbabba','abba','aaaa')
ans =
'aaaaaaaa'
Note that the result has 8 'a's, while 7 'a's are expected. I wonder how can I get the desired result. Thanks so much!

채택된 답변

Voss
Voss 2023년 3월 16일
One way:
oldstr = 'abbabba';
oldp = 'abba';
newp = 'aaaa';
newstr = regexprep(regexprep(oldstr,oldp,newp),oldp,newp);
  댓글 수: 2
Tian
Tian 2023년 3월 16일
It works! Thanks, Voss!
Voss
Voss 2023년 3월 16일
You're welcome!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

태그

제품


릴리스

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by