thamu
thamu

Reputation: 29

How to prepend a single character to a string value in c

I have my code wherein I am supposed to add a character to the beginning of a string.

Here's my string and my character:

char array[12]="12345678"
char var="K"

The value of the finished array must be like this:

array="K12345678"

Currently I have written this like:

char temp[12]={0}
char array[12]="12345678"
char var="K"
strcpy(temp,var);
strncat(temp,array,sizeof(array));
strcpy(array,temp);

Upvotes: 0

Views: 392

Answers (1)

4386427
4386427

Reputation: 44274

First of all notice that

char var="K"

is not correct. To initialize a char do

char var='K';

Then notice that

strcpy(temp,var);

is illegal code as var is not a string but a single char.

You can fix that by doing:

char temp[12]={0};
char array[12]="12345678";
char var='K';
temp[0] = var;  // Put the char as first character of temp
strncat(temp,array,sizeof(array));
strcpy(array,temp);

A better option would be memmove - something like:

// Move the current string 1 to the right (incl. the zero termination)
memmove(array+1, array, strlen(array) + 1);

// Insert the char in front
array[0] = var;

If you don't want to use memmove you can also just do a simple loop:

size_t i = strlen(array);
do
{
    array[i+1] = array[i];
    --i;
} while (i > 0);
array[0] = var;

Upvotes: 2

Related Questions