function extractedText = extractBefore(text,seperator) % Cut text from the beginning of a string up to a seperator % % text is a string, a character array, or a cell array of strings/character arrays % seperator is a single character or a character array. But it can also be % a number N. A cell array containing numbers or charaters is also possible. % % extractedText is text(1:start_position_of_the_first_seperator-1) or % in case of numbers text is cut as text(1:N-1). If text and seperator are % cell arrays they are processed pairwise. % % test the number of input parameters. They have to be exactly 2. if (nargin~=2) print_usage(); endif % free from cell if length is only 1 if (iscell(text) && length(text)==1) text=text{1}; endif if (iscell(seperator) && length(seperator)==1) seperator=seperator{1}; endif % convert parameters if (isstring(text)) text=char(text); % for a octave string implementation endif % test first parameter if (iscell(text)) valid=logical(sum(~cellfun('ischar',text))==0); % all cell entries have to be char arrays else valid=ischar(text); % text has to be char endif if (~valid) error('extractBefore: first argument has to be char or a cell array of chars. For additional information see help extractBefore.'); endif % test second parameter % all cell entries have to be char arrays or numbers if (iscell(seperator)) valid=(sum(~cellfun(@(x) ischar(x)||isscalar(x),seperator,'UniformOutput',true))==0); else valid=ischar(seperator)||isscalar(seperator); endif if (~valid) error('extractBefore: second argument has to be cell, char or number. For additional information see help extractBefore.'); endif % mutual changes if (iscell(seperator) && ischar(text)) text=repmat({text},size(seperator)); % multiply text if seperator is a cell elseif (iscell(text) && (ischar(seperator)||isscalar(seperator))) seperator=repmat({seperator},size(text)); % multiply seperator if text is a cell endif if (iscell(seperator) && iscell(text) && length(seperator)~=length(text)) error('extractBefore: cell length of text and seperator has to match'); endif % cellify to simplify programm flow if (ischar(seperator)||isscalar(seperator)) seperator={seperator}; endif if (ischar(text)) text={text}; endif % do the cuts extractedText=text; if (iscell(extractedText) && iscell(seperator)) n=length(extractedText); for i=1:n if (ischar(seperator{i})) seperator(i)=min(strfind(extractedText{i},seperator{i})); endif if (isempty(seperator(i))) seperator(i)=0; endif if (seperator{i}<=length(extractedText{i})) extractedText(i)=extractedText{i}(1:seperator{i}-1); else error(sprintf('extractBefore: seperator exceeds the text length in position %i.',i)); endif endfor endif % free from cell if length is only 1 if (iscell(extractedText) && length(extractedText)==1) extractedText=extractedText{1}; endif end