How can I convert a string to a text file

13 views (last 30 days)
Josiah Baber
Josiah Baber on 7 Dec 2016
Answered: Stephen23 on 8 Dec 2016
function [output_text] = censor(file)
%This function takes a file text, searches for a four-letter word, and
%replaces the characters with asterisks.
txt = importdata(file);
a = char(txt); % arbitary variable names while transforming into the preferred string format
s = size(a);
file_text = [];
words = [];
indeces = [];
W = []
for i = 1:s(1)
file_text = [file_text a(i,:)]; %takes all of the lines and concatenates them horizontally.
end
for i = 1:length(file_text) %replaces all punctuation with spaces.
if isletter(file_text(i)) == 1
words = [words file_text(i)];
else words = [words ' '];
end
end
for i = 1:length(words) %this for loop locates the indeces of
if isletter(words(i)) == 1 %the characters within the four letter words
W = [W words(i)]
else
if length(W) == 4
indeces = [indeces i-4 i-3 i-2 i-1]; %iterating variable that records the indeces
W = [];
else
W = [];
end
end
end
file_text(indeces) = '*'; %inputs the recorded indeces into the string of words
output_text = char(file_text); %and assigns them to be asterisks
out = [file(1:end-4) '_censored.txt'];
save(out,'output_text')
end

Answers (1)

Stephen23
Stephen23 on 8 Dec 2016
You can read about all file import and export functions here:
In particular look at the low-level functions:
and try this:
fid = fopen(out,'wt');
fprintf(fid,'%s',output_text);
fclose(fid);

Community Treasure Hunt

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

Start Hunting!