Pollardm
Pollardm

Reputation: 13

How to insert multiple chars to the middle of a char array in c?

I'm stuck trying to figure out how I can loop through a char array such as

char line[50] = "this is a string";

and add an extra space every time

line[counter] == ' ';

Thus resulting in the string with all the spaces being twice as long.

Upvotes: 1

Views: 2249

Answers (2)

hm1912
hm1912

Reputation: 314

Here is a solution using another string:

#include <stdio.h>

int main(void) {
  char line[50] = "this is a string";
  char newline[100]; //the new string, i chose [100], because there might be a string of 50 spaces
  char *pline = line;
  char *pnewline = newline;
  while (*pline != NULL) { //goes through every element of the string
    *pnewline = *pline; //copies the string
    if (*pline == ' ') {
      *(++pnewline) = ' '; //adds a space
    }
    pline++;
    pnewline++;
  }
  printf("%s", line);
  printf("%s", newline);
  return 0;
}

If you wouldn't wan't to use up memory, you could do all this with dynamic memory allocation and free() the "temporary" string. I didn't do that now, as you used an array aswell.

Upvotes: 0

Vlad from Moscow
Vlad from Moscow

Reputation: 310980

At first you should count the number of blank characters and then copy backward the string.

For example

#include <stdio.h>

int main(void) 
{
    char s[50] = "this is a string";

    puts( s );

    size_t n = 0;
    char *p = s;

    do
    {
        if ( *p == ' ' ) ++n;
    } while ( *p++ );

    if ( n != 0 )
    {
        char *q = p + n;

        while ( p != s )
        {
            if ( *--p == ' ' ) *--q = ' ';
            *--q = *p;
        }
    }

    puts( s );

    return 0;
}

The program output is

this is a string
this  is  a  string

A more efficient approach is the following

#include <stdio.h>

int main(void) 
{
    char s[50] = "this is a string";

    puts( s );

    size_t n = 0;
    char *p = s;

    do
    {
        if ( *p == ' ' ) ++n;
    } while ( *p++ );

    for ( char *q = p + n; q != p; )
    {
        if ( *--p == ' ' ) *--q = ' ';
        *--q = *p;
    }

    puts( s );

    return 0;
}

Upvotes: 1

Related Questions