J. Doe
J. Doe

Reputation: 345

Insert char into char array C (string)

I got the char array "anana" and I am trying to get a "B" into the beginning in the char array so it spells "Banana" but I cannot wrap my head around how to construct a simple while loop to insert the B and then move every letter one step to the right

Upvotes: 4

Views: 21602

Answers (3)

Shan Ali
Shan Ali

Reputation: 564

Please follow these steps:

  1. Create a new array of size 7 (Banana + terminator). You may do this dynamically by finding the size of the input string using strlen().
  2. Place your desired character say 'B' at newArray[0].
  3. Loop over i=1 -> 7
  4. Copy values as newArray[i] = oldArray[i-1];

Upvotes: 0

Eat at Joes
Eat at Joes

Reputation: 5037

You can use a more traditional approach using...

#include <stdio.h>

int main()
{
  char s[] = "ananas";
  char b[7] = "B";

  for(int i = 0; i < 7; ) {
    char temp = s[i++];
    b[i] = temp;
  }

  printf("%s", b);    

  return 0;
}

Upvotes: 1

jxh
jxh

Reputation: 70392

Assuming:

char array[7] = "anana";

Then:

memmove(array+1, array, 6);
array[0] = 'B';

The memmove function is specifically for cases where the data movement involves an overlap.

Upvotes: 7

Related Questions