REMOVE SPACING IN A STRING
Show older comments
I want to convert my binary data into hex, the function that does so only that string as an input. but when I convert my 64 bit binary matrix into a string, it doesn't remove the spaces, which is messing my solution, any idea how to get rid of these
here is wat im talking about;
what i want: '0111001101100001011001000'
what i get: '0 1 1 1 0 0 1 1 0 1 1 0 0 0 0 1 0 1 1 0 0 1 0 0 0'
4 Comments
AYUSH VARSHNEY
on 31 May 2021
And what about vice versa???
what i want : ''0 1 1 1 1 0 0 0 0 0 1 1 0 0 0" like this from "01110000011100"??
S = "01110000011100"
regexprep(S, '(.)(?=.)', '$1 ')
S = "01110000011100";
sprintf(" %c",S{1})
Walter Roberson
on 5 Jun 2021
But then you have to get rid of the leading space ;-)
Accepted Answer
More Answers (3)
jwiix
on 6 Sep 2018
Edited: Image Analyst
on 6 Jul 2021
As an alternative
A = '0 1 1 1 0 0 1 1 0 1 1 0 0 0 0 1 0 1 1 0 0 1 0 0 0'
A = strrep(A,' ','') % Replace space with null.
It's slightly faster than the current logical indexing answer I think.
-------------------------------------------------------------------------------------------
K>> A= '0 1 1 1 0 0 1 1 0 1 1 0 0 0 0 1 0 1 1 0 0 1 0 0 0'
A =
'0 1 1 1 0 0 1 1 0 1 1 0 0 0 0 1 0 1 1 0 0 1 0 0 0'
K>> tic; A= A(~isspace(A)); toc
Elapsed time is 0.000653 seconds.
-------------------------------------------------------------------------------------------
K>> A= '0 1 1 1 0 0 1 1 0 1 1 0 0 0 0 1 0 1 1 0 0 1 0 0 0'
A =
'0 1 1 1 0 0 1 1 0 1 1 0 0 0 0 1 0 1 1 0 0 1 0 0 0'
K>> tic; A = strrep(A,' ',''); toc
Elapsed time is 0.000098 seconds.
:)
1 Comment
Shep Bryan
on 6 Jul 2021
This answer is much better than the accepted answer
Image Analyst
on 15 Jul 2012
Edited: Image Analyst
on 15 Jul 2012
Just set locations with spaces equal to null:
% Generate sample string.
theString = '0 1 1 1 0 0 1 1 0 1 1 0 0 0 0 1 0 1 1 0 0 1 0 0 0'
% Now change existing string by setting locations with spaces equal to null.
theString(theString == ' ') = []
% Alternative method.
% Create a brand new string with a different name
% by extracting non-space elements.
stringWithoutSpaces = theString(theString ~= ' ')
Akansha Saxena
on 31 Aug 2016
3 votes
requiredString = regexprep(theString, '\s+', '')
2 Comments
Alexander Jensen
on 30 Mar 2018
Edited: Alexander Jensen
on 30 Mar 2018
This also works on cell arrays containing strings! (at least as of version R2017a)
Example:
str = {'1 GC 2 H M', 'food nam nam';'hello world','meh bleb'};
requiredString = regexprep(str, '\s+', '')
requiredString =
2×2 cell array
'1GC2HM' 'foodnamnam'
'helloworld' 'mehbleb'
Thank you
Rajbir Singh
on 10 Jan 2019
its works.
Thank you @Akansha Saxena
Categories
Find more on Data Type Conversion 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!