identifying positions of a string within a text file

5 visualizaciones (últimos 30 días)
Brent
Brent el 1 de Mzo. de 2011
I would like to take a text file, which has been saved with various special characters ('e.g. $$') and identify the positions that these characters occupy. Then, I would insert values into those positions. So the file may look like: line $$ 1 $$ line 2
So I would need some way to identify positions 6 and 11, then insert text at those locations.
I've tried various things such as reading the file in a string and converting to a char array while using strfind, but in each case, there is an issue. What would be the best way to overwrite the $$'s with values?
Thanks

Respuesta aceptada

Walter Roberson
Walter Roberson el 1 de Mzo. de 2011
Probably something like this:
fid = fopen(FileName,'rt');
filetext = fread(fid,'*char');
fclose(fid);
newtext = regexprep(filetext, '\$\$', 'Hello', 'once');
newtext = regexprep(newtext, '\$\$', 'World', 'once');
fid = fopen(NewFilename, 'wt');
fwrite(fid, newtext, '*char');
fclose(fid);

Más respuestas (2)

Brett Shoelson
Brett Shoelson el 1 de Mzo. de 2011
Lots of ways. This one uses regular expressions:
mystr = 'line $$ 1 $$ line 2'
newstr = regexprep(mystr,'\$\$','New_String')
Cheers,
Brett

Brent
Brent el 1 de Mzo. de 2011
Thank you both for the quick reply. This is exactly what I needed.

Categorías

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

Community Treasure Hunt

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

Start Hunting!

Translated by