views:

428

answers:

2

My char array would be looking something like below,

Org_arr[1first line text------2second line text----3third line-------4--------------------5fith line text------];

where '-' equal to blank spaces

The above array contains the control code(0, 1, 2, 3..) after every 20 characters starting from 0-th place.

I would like to convert the above text array into below format,

The blank spaces will be removed and a line feed will be added at the end of each line.

Conv_arr[1first line text/n2second line text/n3third line/n4/n5fith line text/n];

Please suggest me a good method to implement this,

Thank You

+1  A: 

the easiest way will be using regular expression to replace pattern "\s?" with "\n"

If you don't have access to a regex library, you can do something like this

int print_line_break = 1;
char* Conv_arr = (char*)malloc(sizeof(char) * strlen(Org_arr) + 1);

for(char* c=Org_arr; *c; ++c) {
   if (*c == ' ') {
      *(Conv_arr++) = *c;
      print_line_break = 1;
   } else {
      // only print 1 '\n' for a sequence of space
      if (print_line_break) {
         *(Conv_arr++) = '\n';
         print_line_break = 0; 
      }
   }
}

free(Conv_arr);
oykuo
Don't cast the return value of malloc as it can hide failure to include stdlib.h (this is C after all). Also, `sizeof char` is always 1 so there is no need to use that in the argument to malloc. Finally, why are you freeing Conv_arr?
Sinan Ünür
* Thank for the malloc cast tip, I didn't know this* I do sizof(char) because it is a compile time construct and has no run time performance hit anyway and I reckon it is a good practise.* I should have included "..." above free() I just stress the fact that Conv_arr is malloc-ed and should be freed later
oykuo
@kuoson I understand now why you put free(Conv_arr).
Sinan Ünür
A: 

This code is ugly and smells funny:

#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    int c;
    char *src, *tgt;
    char mystr[] = "1first line text      "
        "2second line text    "
        "3third line       "
        "4                    "
        "5fith line text      ";

    char *cur = mystr;
    char *prev = NULL;

    while ( ( c = *cur++ ) ) {
        if ( c != ' ' && *cur == ' ' ) {
            prev = cur;
            continue;
        }
        if ( c == ' ' && isdigit(*cur) ) {
            *prev++ = '\n';
            src = cur;
            tgt = prev;
            while ( ( *tgt++ = *src++ ) );
            cur = prev;
        }
    }

    puts( mystr );
    return 0;
}

[sinan@archardy]$ ./t
1first line text
2second line text
3third line
4
5fith line text
Sinan Ünür