1

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.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Pollardm
  • 13
  • 5
  • 2
    the easiest way would probably be creating another array and write the result there. – Kami Kaze Feb 10 '17 at 11:06
  • 1
    you have to insert the space and shift all characters after that space explicitly at each loop step. of course you can use a temp copy while doing it. – Shiping Feb 10 '17 at 11:08
  • Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers. See: How to create a Minimal, Complete, and Verifiable example. – too honest for this site Feb 10 '17 at 11:37
  • 2
    We are no "gimme teh codez" site. Where **specifically** are you stuck? See [ask] and provide a [mcve]. – too honest for this site Feb 10 '17 at 11:37

2 Answers2

1

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;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

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.

hm1912
  • 314
  • 1
  • 10