5

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.

2
  • How do you identify where the blanks should go? A set of indices for the output array? A set of indices for the input array to add the blanks after? Commented Apr 6, 2011 at 17:43
  • I have an array of indexes [7, 12 .... and I want to put white space there and "move horizonatly" the rest of the string" Commented Apr 6, 2011 at 17:46

2 Answers 2

5

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
Sign up to request clarification or add additional context in comments.

3 Comments

thx but this is not execly what I wanted, maybe I wasn't clear. It puts 7 correctly, but 12 index is taken form the new array with a space - Should be ABCDEF GHJKL MNO.
@lukas: I've updated my answer, so it should work for you now. You should probably edit the question to add the extra detail about your indexing scheme.
awesome. I need it for this stackoverflow.com/questions/5558005/…
2

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)];

1 Comment

This works for the specific example, but how would it generalize to an arbitrary set of indices?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.