how to split a string

조회 수: 132 (최근 30일)
Mitchie Teotico
Mitchie Teotico 2020년 3월 28일
답변: DGM 2022년 5월 22일
i need to create a function named breakline which inputs a string (char, 1 × N) and a linewidth (integer, scalar). The function then splits the string into smaller strings which are smaller than the linewidth.
The output to the function is an array which contains all of the split up lines (cell array, 1 × M).
for example
out=breakupLine(123456789,4)
out =
{
[1,1] = 1234
[1,2] = 5678
[1,3] = 9
}
  댓글 수: 1
Walter Roberson
Walter Roberson 2020년 3월 28일
It is not possible to get the output in exactly that format. The initial part showing the index can only appear if you create the output as all one character vector, contradicting the requirement that it be a cell array.

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

답변 (4개)

Walter Roberson
Walter Roberson 2020년 3월 28일
If the current vector is shorter than N or exactly N then add the complete current vector to the end of the cell array and return. Otherwise index the first N characters from the current vector and add them to the end of the cell array, and remove N characters from the beginning of the current vector overwriting the current vector and loop back.
  댓글 수: 2
Mitchie Teotico
Mitchie Teotico 2020년 3월 29일
could you show an example
Walter Roberson
Walter Roberson 2020년 3월 29일
ThisRow = RemainingLetters(1:4);
RemainingLetters = RemainingLetters(5:end);

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


Nik Niki
Nik Niki 2022년 5월 22일
편집: Image Analyst 2022년 5월 22일
test_data_name="kjashfk, kjasdklasdfas, 3";
test_data_name = split(test_data_name)
test_data_name = 3×1 string array
"kjashfk," "kjasdklasdfas," "3"

Image Analyst
Image Analyst 2022년 5월 22일
Here is one way:
out=breakupLine('123456789', 4)
out = 1×3 cell array
{'1234'} {'5678'} {'9'}
%=====================================================
function out=breakupLine(str, substringLength)
stringLength = length(str);
loopCounter = 1;
for k = 1 : substringLength : stringLength
index1 = k;
index2 = min(k + substringLength - 1, stringLength);
out{loopCounter} = str(index1 : index2);
loopCounter = loopCounter + 1;
end
end

DGM
DGM 2022년 5월 22일
To address the OP's particular request:
linew = 4;
teststr = '123456789';
excess = rem(numel(teststr),linew);
output = reshape(teststr(1:end-excess),linew,[]).';
output = [num2cell(output,2); teststr(end-excess+1:end)]
output = 3×1 cell array
{'1234'} {'5678'} {'9' }
I don't know that this is particularly efficient, but it works. It may have advantages at some scale, but I haven't tested that.

카테고리

Help CenterFile Exchange에서 Cell Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by