Split a string into 4 character groups?

14 views (last 30 days)
darren Clipson
darren Clipson on 24 Apr 2021
Edited: per isakson on 24 Apr 2021
Hello,
I am writing a program as part of my foundation degree which takes messages and encrypts them in a basic way. So far I have used a .txt file encoded in the ASCII format and maniuplated each character to output a single line string based upon the length of the original message:
n=1:length(number_message)
the variable 'number_message' is the output variable in my code. As this string could potentially be any length (n), how can I reliably split this output string into groups of characters for further processing?
My program design is to use multiple layers and I want to group at this stage to deal with the data in groups before moving on to a potential HEX conversion.
I am quite new to Matlab, and coding in general so this may seem like a bit of a strange question and may not make sense.
Kind Regards
_message)

Accepted Answer

per isakson
per isakson on 24 Apr 2021
Edited: per isakson on 24 Apr 2021
"Split a string into 4 character groups?", "split this output string into groups of characters" and "I want to group at this stage to deal with the data in groups"
%% cssm.txt contains the text of your question
chr = fileread( 'cssm.txt' );
%% replace line breaks with spaces
chr = strrep( chr, char(13), '' );
chr = strrep( chr, newline, char(32) );
%%
group_len = 4;
len = numel( chr );
d = rem( len, group_len );
chr = horzcat( chr, repmat( char(32), 1, group_len-d ) );
chr = reshape( chr, 4,[] );
chr(:,1:12) % the groups are column wise
ans = 4×12 char array
'Ho wiaom t f' 'e,arn g p mo' 'l migpraaoyu' 'lI t rasrf n'
%% easier to read, but somewhat less efficient
chr = permute( chr, [2,1] );
chr(1:12,:) % the groups are row wise
ans = 12×4 char array
'Hell' 'o, I' ' am ' 'writ' 'ing ' 'a pr' 'ogra' 'm as' ' par' 't of' ' my ' 'foun'

More Answers (1)

darren Clipson
darren Clipson on 24 Apr 2021
I think I have found an alternate path to progress moving the data over to binary using the dec2bin command I can create an array of binary characters arranged in a 172x7 array.
To achive this I used:
number_message2 = dec2bin(number_message)
number_message3 = bin2dec(number_message2)
This code switches between the 2 message formats and I think I can further manipulate the data from its binary form. I'm certain I will need to ask further questions to achieve this but i'm not entirely sure what my plans are going to be at this stage.
Feel free to add any input if you feel it nessessary.
Regards

Products


Release

R2021a

Community Treasure Hunt

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

Start Hunting!