% string functions help strfun % opening a file help fopen % reading a line of a file help fgetl % reading in file one line at a time. fid = fopen('/Users/tlberg/Desktop/teaching/Spring_10/demos/textProc/text.txt','r'); while 1 tline = fgetl(fid); if ~ischar(tline), break, end tline end fclose(fid); % what if we want to split each line into individual words help strtok fid = fopen('/Users/tlberg/Desktop/teaching/Spring_10/demos/textProc/text.txt','r'); count=0; while 1 tline = fgetl(fid); if ~ischar(tline), break, end r = tline; while ~isempty(r) [t,r] = strtok(r); t end end % now let's find which of those words are the word 'text' fid = fopen('/Users/tlberg/Desktop/teaching/Spring_10/demos/textProc/text.txt','r'); count=0; while 1 tline = fgetl(fid); if ~ischar(tline), break, end r = tline; while ~isempty(r) [t,r] = strtok(r); if strcmp(t,'text') count=count+1; end end end fclose(fid); count % find all occurences of the word text and don't care about capitalization help strcmpi fid = fopen('/Users/tlberg/Desktop/teaching/Spring_10/demos/textProc/text.txt','r'); count=0; while 1 tline = fgetl(fid); if ~ischar(tline), break, end r = tline; while ~isempty(r) [t,r] = strtok(r); if strcmpi(t,'text') count=count+1; end end end fclose(fid); count % find all occurences of the substring text even if it's part of another word fid = fopen('/Users/tlberg/Desktop/teaching/Spring_10/demos/textProc/text.txt','r'); count=0; while 1 tline = fgetl(fid); if ~ischar(tline), break, end a = strfind(tline,'text'); if ~isempty(a) count=count+length(a); end end fclose(fid); count % what if we want to read each line into a cell array for later processing fid = fopen('/Users/tlberg/Desktop/teaching/Spring_10/demos/textProc/text.txt','r'); lines = []; while 1 tline = fgetl(fid); if ~ischar(tline), break, end lines{end+1} = tline; end fclose(fid); length(lines) % what if we want to read each non-empty line into a cell array fid = fopen('/Users/tlberg/Desktop/teaching/Spring_10/demos/textProc/text.txt','r'); lines = []; while 1 tline = fgetl(fid); if ~ischar(tline), break, end if ~isempty(tline) lines{end+1} = tline; end end fclose(fid); % show lines in array lines{1} lines{2} lines{3} length(lines) % find a particular string in your array inds = strcmp(lines,'For texting language, see SMS language.'); inds ind = find(inds); ind lines{ind}; % can directly index into strings a = lines{8}; a a(4:20) % character 4 through end of string a(4:end) b = lines{5}; b % can easily concatenate strings c = [a b]; c % can set substrings to new strings easily b b(4:11+3) = ['hello world']; a = 'LSkJLkJ' a lower(a) upper(a) help strrep b = strrep(b,'hello','goodbye'); b