Creating a Function that acts as a counter for certain string
    조회 수: 5 (최근 30일)
  
       이전 댓글 표시
    
Okay, I am trying to create a function that reads a txt. file then for every certain string counts it as one until it reaches 10. Then the 10th string is taken and placed in an array. Can anyone help me?
답변 (1개)
  BhaTTa
 2024년 1월 19일
        Hey @Frandy , In MATLAB, you can create a function to read a text file, count occurrences of a specific string, and collect every 10th occurrence into an array. Here's an example function that does this:
function resultArray = collectEveryTenthOccurrence(filename, searchString)
    % Initialize the counter and the result array
    occurrences = 0;
    resultArray = {};
    % Open the text file for reading
    fid = fopen(filename, 'rt');
    if fid == -1
        error('File cannot be opened: %s', filename);
    end
    % Read the file line by line
    while ~feof(fid)
        line = fgetl(fid);
        words = strsplit(line); % Split the line into words
        for i = 1:length(words)
            word = words{i};
            % Check if the word matches the search string
            if strcmp(word, searchString)
                occurrences = occurrences + 1;
                % If the 10th occurrence, add to the result array
                if mod(occurrences, 10) == 0
                    resultArray{end+1} = word;
                end
            end
        end
    end
    % Close the file
    fclose(fid);
end
To use this function, you would call it with the filename and the search string as arguments, like so:
collectedWords = collectEveryTenthOccurrence('sample.txt', 'example');
disp(collectedWords);
Hope it helps!
댓글 수: 0
참고 항목
카테고리
				Help Center 및 File Exchange에서 Characters and Strings에 대해 자세히 알아보기
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!


