hi, how to use strsplit function to split a line of string into multiple lines when a predefined number of characters is reached?

for example: if I have: "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", I want to split it into lines after 4 characters and then I could have:"AAAA" "AAAA" "AAAA" "AAAA"

 채택된 답변

This divides them into 8 rather than 4 strings:
str = 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA';
SplitLen = 4;
CheckLen = SplitLen*fix(length(str)/SplitLen); % So ‘reshape’ Will Work
Result = {reshape(str(1:CheckLen), [], 4)}; % Result As Cell Array

댓글 수: 6

BUT! instead of saying to split into n strings, I want to split into strings of length l, so i don't know how many strings I will have at the end!
I forgot to include ‘SplitLen’ as an argument to reshape. The result is unchanged:
str = 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA';
SplitLen = 4; % Length Of Strings
CheckLen = SplitLen*fix(length(str)/SplitLen); % So ‘reshape’ Will Work
Result = {reshape(str(1:CheckLen), [], SplitLen)}; % Result As Cell Array
still it does not work, because if the length of remainder of string is less than what was defined it will be ignored and i don't want this
The string argument to reshape has to be an integer multiple of the desired length of the substrings. The easiest way to deal with the remainder of the string is to append it to the end:
Result = {reshape(str(1:CheckLen), [], SplitLen); str(CheckLen+1:end)};

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

s=reshape(s,L,[]);
Requires rem(length(S)/L)=0, of course.

댓글 수: 1

So the safest thing is to precede the code with:
assert(mod(numel(s), L) == 0, 'String length is not a multiple of the split-length');

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Characters and Strings에 대해 자세히 알아보기

태그

질문:

2015년 9월 17일

댓글:

2015년 9월 17일

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by