Hi,
The naive approach would be to convert everything to lowercase and then replace, but the problem is in the obtained output file as every word is lowercase which is not expected with actual output (Lab5Demo.txt).
Here’s the sample code (specific to this example) that does the same job without converting into lowercase.
function [] = Assign5()
clc;clear
[tag,replacement] = read_sub_tag();
create_output(replacement);
end
function [tag,replacement] = read_sub_tag()
tag = [];
replacement = [];
fname = fopen('sub.txt','r');
[tag,replacement] = strtok(fgets(fname));
tag = lower(tag);
replacement = strtrim(replacement);
fclose(fname);
end
functioncreate_output(replacement)
Original_File = fopen('form.txt','r') ;
Modified_File = fopen('Lab5Demo.txt','w');
while ( ~feof(Original_File) )
str = fgets(Original_File);
% Compare what with any of {what,WHAT,What,......} by making case insensitive(?i)
match = regexp(str, '(?i)what(?-i)') ;
i = length(match);
while (~isempty(match) && i>0)
% In this example to replace [what?] with thought with help of indexes.
newStr = replaceBetween(str,match(i)-1,match(i)-1+6,replacement);
str = newStr;
i=i-1;
end
fprintf(Modified_File,newStr) ;
end
fclose(Original_File);
fclose(Modified_File);
end
I hardcoded the tag string to get it done as this is just a sample code. You can try making this a generalized one with the help of regex. You can also use regexprep once you’re comfortable with regex and get the whole line at once without looping for each match.
Hope this helps.