In Matlab, how can you code that if a string has any of a certain set of specifi
ID: 3849621 • Letter: I
Question
In Matlab, how can you code that if a string has any of a certain set of specific words, to replace them with a different word. For example, the first set of "problem" words, {'Joe' 'coffee' and 'chocolate' } are found from text file 1 and their replacement words are found from text file 2 in the format of the problem word first followed by the replacement (< problemword >: < replacement >). Each text file can have these words multiple times in them throughout the file and they can be on the same line as well. I made a switch case, but I don't know how to actually find where these words are and replace the words with the replacement words after pulling them out of text file 2.
Explanation / Answer
Answer for the Question:
Using regexprep is probably better than strrep.
See the below example code how regexprep and strrep will works:
s='111111111'; % six + three '1'
regexprep(s,'111111','123456') % replace six '1' by '123456'
strrep(s,'111111','123456')
This below code may give the better understanding and how to replace
given set of problems words with second file
We need to write the modified text to a different file:
fin = fopen('file1.txt');
fout = fopen('file2.txt');
while ~feof(fin)
s = fgetl(fin);
s = strrep(s, 'hello', 'world');
fprintf(fout,'%s',s);
disp(s)
end
fclose(fin)
close(fout)
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.