Macaronnos
Macaronnos

Reputation: 647

Replace substring that lies between two positions

I have a string S in Matlab. How can I replace a substring in S with some pattern P. I only know the first and the last index of substring in S. What is the approach?

Upvotes: 1

Views: 61

Answers (1)

Robert Seifert
Robert Seifert

Reputation: 25232

How about that?

str = 'My dog is called Jim';      %// original string  

a = 4;                             %// starting index
b = 6;                             %// last index

replace = 'hamster';               %// new pattern

newstr = [str(1:a-1) replace str(b+1:end)]

returns:

newstr =  My hamster is called Jim

In case the pattern you want to substitute has the same number of characters as the new one, you can use simple indexing:

str(a:b) = 'cat'

returns:

str =  My cat is called Jim

Upvotes: 1

Related Questions