Replace characters in strings that meet a condition

조회 수: 6 (최근 30일)
Paul Martin
Paul Martin 2025년 4월 2일
댓글: Paul Martin 2025년 4월 2일
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

채택된 답변

Suraj Kumar
Suraj Kumar 2025년 4월 2일
편집: Suraj Kumar 2025년 4월 2일
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
Paul Martin
Paul Martin 2025년 4월 2일
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

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

추가 답변 (0개)

카테고리

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

태그

제품


릴리스

R2024b

Community Treasure Hunt

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

Start Hunting!

Translated by