Replace characters in strings that meet a condition

5 visualizaciones (últimos 30 días)
Paul Martin
Paul Martin el 2 de Abr. de 2025
Comentada: Paul Martin el 2 de Abr. de 2025
I have a 1x5 string array:
myStrings = [ "HH RBPMS", "HH RBPMS", "HH SCGN", "HH RBPMS", "HH ChAT" ];
I would like to replace the characters "HH" with the characters "CT" in the strings which contain the characters "ChAT".
It seems that this should be a simple problem with a simple answer, but it's causing me misery:
contains(myStrings, 'ChAT")
returns a logical array, but I can't see how to use that array to do the replace operation on all the strings in the array.
With apologies for my dim-wittedness and thanks for any suggestions,
Paul Martin

Respuesta aceptada

Suraj Kumar
Suraj Kumar el 2 de Abr. de 2025
Editada: Suraj Kumar el 2 de Abr. de 2025
Hi Paul,
To replace the characters 'HH' in the strings we can use logical indexing with the contains function to identify which strings contain "ChAT" and then apply the replace function on those strings.
myStrings = ["HH RBPMS", "HH RBPMS", "HH SCGN", "HH RBPMS", "HH ChAT"];
index = contains(myStrings, "ChAT");
myStrings(index) = replace(myStrings(index), "HH", "CT");
disp(myStrings);
"HH RBPMS" "HH RBPMS" "HH SCGN" "HH RBPMS" "CT ChAT"
This code snippet will search for the substring "ChAT" in each element of myStrings, then replace "HH" with "CT" only in those elements that contain "ChAT".
To learn more about the replace function in MATLAB, please refer to the following documentation:
Hope this resolves your query!
  1 comentario
Paul Martin
Paul Martin el 2 de Abr. de 2025
Thank you!
As usual, the answer was staring me in the face ... it was the assignment using myStrings(index) = ... that had slipped my mind.
Thanks again,
Paul

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Characters and Strings en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2024b

Community Treasure Hunt

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

Start Hunting!

Translated by