replacing text in a string using indexing

조회 수: 14 (최근 30일)
Lin
Lin 2022년 9월 21일
편집: Stephen23 2022년 9월 21일
how could replace text by just using one line of code
e.g. a = 'qqqqqq' and I want to make q = 'qweqwe'

답변 (2개)

Mathieu NOE
Mathieu NOE 2022년 9월 21일
I win the prize !
out = strrep('qqqqqq','qqqqq','qwe')
out =
'qweqwe'
  댓글 수: 2
Lin
Lin 2022년 9월 21일
thanks !
but what if i want to make 'qqqqqqqqqq' to 'qweqweqweq'
sorry for the dumb question, still a rookie and have a hard beginning using matlab
Mathieu NOE
Mathieu NOE 2022년 9월 21일
look at the doc for function strrep
strrep Find and replace substring.
MODIFIEDTEXT = strrep(ORIGTEXT,OLDSUBTEXT,NEWSUBTEXT) replaces all
occurrences of the text OLDSUBTEXT within text ORIGTEXT with the
text NEWSUBTEXT.
the trick here is to count how many times you want the pattern 'qwe' repeated in the output (modified) text
you last query request 3 time 'qwe' to make 'qweqweqweq' so we will take the input text ('qqqqqqqqqq') and remove 3 - 1 = 2 'q' from this character to create the subtext
here a liitle demo where I remove 0,1,2 times the q
out1 = strrep('qqqqqqqqqq' ,'qqqqqqqqqq' ,'qwe') % zero 'q' removed in subtext (compared to input text)
out2 = strrep('qqqqqqqqqq' ,'qqqqqqqqq' ,'qwe') % one 'q' removed in subtext
out3 = strrep('qqqqqqqqqq' ,'qqqqqqqq' ,'qwe') % two 'q' removed in subtext
out1 = 'qwe'
out2 = 'qweqwe'
out3 = 'qweqweqwe'

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


Stephen23
Stephen23 2022년 9월 21일
편집: Stephen23 2022년 9월 21일
For overlapping matches use STRREP.
For non-overlapping matches use REGEXPREP:
regexprep('qqqqqq','qqq','qwe')
ans = 'qweqwe'
regexprep('qqqqqqqqq','qqq','qwe')
ans = 'qweqweqwe'

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by