Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert white spaces into char array

I have char array(vector) of chars and I want to insert white spaces in specific order.

For example I have

 ['A','B','C','D','E','F','G','H','J','K','L','M','N','O']

and vector with indexes of white spaces

[7 12] % white spaces should be add to 7 and 12 indexes (original string)

and want to have

 ['A','B','C','D','E','F',' ','G','H','J','K', 'L', ' ','M','N','O']

Is there some build-in function? I started with nested loop to itarate the array and instert ' ', but it looks ugly.

like image 721
Lukasz Madon Avatar asked Apr 06 '11 17:04

Lukasz Madon


People also ask

Can we store space in character array?

If you are really keen on using a single character array for storing white spaces as well, then you could make use of the gets( ) function. In this program, you can enter a name with blank spaces and that will also be stored in the array 'name'.

Can chars store spaces?

The length of a CHAR column is fixed to the length that you declare when you create the table. The length can be any value from 0 to 255. When CHAR values are stored, they are right-padded with spaces to the specified length.


2 Answers

If you have indices into your vector where you want the blanks to be inserted, you could do the following:

>> str = 'ABCDEFGHJKLMNO';                %# Your string
>> index = [7 12];                        %# Indices to insert blanks
>> index = index+(0:numel(index)-1);      %# Adjust for adding of blanks
>> nFinal = numel(str)+numel(index);      %# New length of result with blanks
>> newstr = blanks(nFinal);               %# Initialize the result as blanks
>> newstr(setdiff(1:nFinal,index)) = str  %# Fill in the string characters

newstr =

ABCDEF GHJKL MNO
like image 60
gnovice Avatar answered Sep 22 '22 05:09

gnovice


Do you want to insert spaces at specific indices?

chars = ['A','B','C','D','E','F','G','H','J','K','L','M','N','O'];
%insert space after index 6 and after index 10 in chars
charsWithWhitespace = [chars(1:6), ' ', chars(7:10), ' ', chars(11:end)];
like image 42
sverre Avatar answered Sep 19 '22 05:09

sverre