用C

2009-06-08 52 views
0
從字符數組修剪空格

我的字符數組將尋找類似下面,用C

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

其中「 - 」等於空格

上述數組包含的控制代碼(0 ,1,2,3 ..)從第0位開始每20個字符後。

我想上述文本陣列轉換成下面的格式,

的空格都將被刪除和換行會在每一行的結束時加入。

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

請建議實行一個很好的方法,

+1

有不是你的例子中每個數字之間的20個字符...... – Stephan202 2009-06-08 22:08:41

回答

1

最簡單的方法將使用正則表達式替換模式「\ s?」爲「\ n」

如果你沒有獲得一個正則表達式庫,你可以做這樣的事情

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); 
+0

*感謝malloc轉換提示,我不知道這 *我做sizof(char),因爲它是一個編譯時構造,沒有運行時間無論如何我的表現都很出色,我認爲這是一個很好的做法。 *我應該包括「...」高於free()我只強調Conv_arr是malloc-ed的事實,應該稍後釋放 – oscarkuo 2009-06-08 23:53:14

0

此代碼是醜陋和氣味好笑:

#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; 
} 

[[email protected]]$ ./t 
1first line text 
2second line text 
3third line 
4 
5fith line text