1

我正在尝试使用以下代码在 matlab 的文本文件中搜索 hello:

 fid = fopen(filename, 'r');
 if (fid == -1) 
    error('cnt open');
 end

 i = 0;
 while (i == 0)

    str = 'hello';
    validStrings = fgets(fid);
     validStr = validatestring(str,validStrings);
    disp(validStr)
    if (line == -1) 
      i = 1;
    else
    fprintf(1, '%s', line);
    end

 end

 fclose(fid);

在这种情况下我可以不使用 validStrings 吗?我收到错误

??? Error using ==> validatestring
Valid strings must be a cell array of strings.
4

1 回答 1

0

该函数需要一个字符串单元:

A = cell(100,1); // use a bigger number if you have a large file
while (i == 0)
    str = 'hello';
    validStrings = fgets(fid);
    j = 1;
    [A{j} remain] = strtok(validStrings, ' '); //or other delimiter than spaces
    while(size(remain,2) ~= 0)
        [A{j} remain] = strtok(str, ' ');
        j = j+1;
    end
    validStr = validatestring(str,A);
    disp(validStr)
    if (line == -1) 
        i = 1;
    else
        fprintf(1, '%s', line);
    end
end
于 2012-12-11T21:40:36.353 回答