首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >计算以特定字符串- Matlab开头的行数。

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

Stack Overflow用户
提问于 2014-09-26 08:44:33
回答 2查看 715关注 0票数 2

我想计数文本文件中仅以特定字符串开头的字符串数。

代码语言:javascript
复制
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’开头的行)。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-09-26 10:40:09

您可以在这里尝试两种基于importdata的方法。

方法#1

代码语言:javascript
复制
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

代码语言:javascript
复制
%// ..... 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数组指定为搜索字符串。

票数 0
EN

Stack Overflow用户

发布于 2014-09-26 09:08:39

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

代码语言:javascript
复制
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的值。

另外,我不知道这两种方法的性能问题是什么。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26055507

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档