计算以特定字符串开头的行数 - Matlab

时间:2014-09-26 08:44:34

标签: matlab

我想计算一个文本文件中以特定字符串开头的字符串数

function count = countLines(fname)
fh = fopen(fname, 'rt');
assert(fh ~= -1, 'Could not read: %s', fname);
x = onCleanup(@() fclose(fh));
count = 0;
while ~feof(fh)
count = count + sum( fread( fh, 16384, 'char' ) == char(10) );
end
count = count+1;
end

我使用上面的函数来计算整个.text文件中的行数。但现在我想找到仅以特定字符串开头的行数(例如,所有以字母's开头的行)。

2 个答案:

答案 0 :(得分:0)

虽然我不了解您的代码背后的想法,所以我无法修改它我使用这种方法:

fid = fopen(txt);

% Loop through data file until we get a -1 indicating EOF
while(x ~= (-1))
    line = fgetl(fid);
    r = r+1;
end
r = r-1;

r是文件中的行数。您可以在增加计数器line之前轻松检查r的值,以便首先满足您的条件。

此外,我不知道有关这两种方法的性能问题。

答案 1 :(得分:0)

您可以在此处尝试两种 importdata 方法。

方法#1

str1 = 's';  %// search string 

%// Read in text data into a cell array with each cell holding text data from 
%// each line of text file
textdata = importdata(fname,'\n') ;

%// Compare each cell's  starting n characters for the search string, where 
%// n is no. of chars in search string and sum those matches for the final count
count = sum(cellfun(@(x) strncmp(x,str1,numel(str1)),textdata)) 

方法#2

%// ..... Get str1 and textdata as shown in Approach #1

%// Convert cell array data into char array
char_textdata = char(textdata) 

%// Select the first n columns from char array and compare against search
%// string for all characters match and sum those matches for the final count.
%// Here n is the number of characters in search string
count = sum(all(bsxfun(@eq,char_textdata(:,1:numel(str1)),str1),2))

使用这两种方法,您甚至可以将char数组指定为搜索字符串。