How do i cut a string after an amount of values or a delimiter
Show older comments
Hey was hoping someone could help me out here.
I have a string lets say:
1 2 3 4 5 6; 7 8 9 10 11 12; 13 14 15 16 17 18
Now i want to make a new string that always cuts of after the first 5 values until it reaches the ;. So in this case I would get an output like
1 2 3 4 5
6
7 8 9 10 11
12
13 14 15 16 17
18
Any help would be appreciated...
Roger
1 Comment
"String" means a vector of type char in Matlab. Your data look like a matrix instead. Or do you mean:
Str = '1 2 3 4 5 6; 7 8 9 10 11 12; 13 14 15 16 17 18'
?? Should the new "string" be a cell string or a string, which contains line break characters?
Accepted Answer
More Answers (4)
Jos (10584)
on 14 Oct 2013
Edited: Jos (10584)
on 14 Oct 2013
Something along these lines, perhaps (untested!):
% data:
str = '1 2 3 4 5 6; 7 8 9 10 11 12; 13 14 15 16 17 18'
TextToInsert = {'Text','Another line'}
% engine:
ss = strread(str,'%s','delimiter',';') ;
C = {} ;
t2i_counter = 1 ;
for k1=1:numel(ss),
X = str2num(ss{k1}) ;
nX = numel(X) ;
for k2=1:5:nX
C{end+1} = X(k2:min(k2+4,nX)) ;
end
if t2i_counter < numel(TextToInsert)
C(end+1) = TextToInsert(t2i_counter) ;
t2i_counter = t2i_counter + 1 ;
else
C{end+1} = 'Default insert text' ;
end
end
% result:
C{:}
Jan
on 14 Oct 2013
Str = '1 2 3 4 5 6; 7 8 9 10 11 12; 13 14 15 16 17 18'
Str = strrep(Str, ';', '');
CStr = regexp(Str, ' ', 'split');
NL = char(10);
Header = {'stringnumber1', 'Text', 'Another line'};
CStr(1:6:end) = strcat(Header, NL, CStr(1:3:end));
CStr(5:6:end) = strcat(CStr(5:6:end), NL);
CStr(6:6:end) = strcat(CStr(6:6:end), NL);
fprintf('%s ', CStr{:})
(Not tested!)
Categories
Find more on Standard File Formats in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!