Effacer les filtres
Effacer les filtres

How can I replace a certain pattern in a string?

2 vues (au cours des 30 derniers jours)
Tian
Tian le 16 Mar 2023
Commenté : Voss le 16 Mar 2023
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!

Réponse acceptée

Voss
Voss le 16 Mar 2023
One way:
oldstr = 'abbabba';
oldp = 'abba';
newp = 'aaaa';
newstr = regexprep(regexprep(oldstr,oldp,newp),oldp,newp);
  2 commentaires
Tian
Tian le 16 Mar 2023
It works! Thanks, Voss!
Voss
Voss le 16 Mar 2023
You're welcome!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Characters and Strings dans Help Center et File Exchange

Produits


Version

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by