How can I replace a certain pattern in a string?

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!

 Respuesta aceptada

Voss
Voss el 16 de Mzo. de 2023
One way:
oldstr = 'abbabba';
oldp = 'abba';
newp = 'aaaa';
newstr = regexprep(regexprep(oldstr,oldp,newp),oldp,newp);

2 comentarios

Tian
Tian el 16 de Mzo. de 2023
It works! Thanks, Voss!
Voss
Voss el 16 de Mzo. de 2023
You're welcome!

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Characters and Strings en Centro de ayuda y File Exchange.

Productos

Versión

R2020a

Etiquetas

Preguntada:

el 16 de Mzo. de 2023

Comentada:

el 16 de Mzo. de 2023

Community Treasure Hunt

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

Start Hunting!

Translated by