remove character within a string

조회 수: 7 (최근 30일)
Maria
Maria 2020년 9월 15일
답변: Walter Roberson 2020년 9월 15일
code error for removing loc(character) from birds(string). loc ensure has three letters.
function [nm, couriers] = ostrichExpress(birds, loc)
ind=strfind(birds,loc);
nm=length(ind);
birds(ind:ind+2)=[]; %error
couriers=birds;
end
  댓글 수: 2
KSSV
KSSV 2020년 9월 15일
Give one example....wfrom what string what you are trying to remove?
Maria
Maria 2020년 9월 15일
'DJI GHA MOZ DJI NER NER NER GHA ' remove 'NER'

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

채택된 답변

KSSV
KSSV 2020년 9월 15일
s1 = 'DJI GHA MOZ DJI NER NER NER GHA ' ;
s2 = 'NER' ;
s1 = strsplit(s1) ;
idx = ismember(s1,s2) ; % get the strings present
s1(idx) = [] ; % remove the strings
s1 = strjoin(s1)

추가 답변 (1개)

Walter Roberson
Walter Roberson 2020년 9월 15일
s1 = regexprep(s1, 'NER\s*', '')
This deletes all occurances of NER with following whitespace.
This particular code does not delete leading whitespace. And that means that if you happen to have
s1 = 'DJI GHA MOZ DJI GHA NER'
that the result would be
'DJI GHA MOZ DJI GHA ' %with trailing space
If you code to delete leading whitespace instead of trailing whitespace, you end up with a similar problem if the string happens to start with 'NER'.
If you code it to delete both leading and trailing whitespace then you risk joining adjacent items that are not NER.
KSSV's code does not have this difficulty of leaving in whitespace. On the other hand, KSSV's code does not preserve whitespace size, always substituting a single blank for all whitespace.
DJI GHA MOZ NER GHA
would be changed to
DJI GHA MOZ GHA
It is not easy to define what the right answer "should" be when there are variable amounts of whitespace.

카테고리

Help CenterFile Exchange에서 Clocks and Timers에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by