2017-06-07 17 views
0

給定一個存在於數組中的行。像在這種情況下:在給定從一些文件(或標準輸入)的行我怎麼能減少額外的空間並將標籤轉換爲單個空間?

char line[50]; 
while (fgets(line,50, input_file) != NULL) { 
// how can i do it here.. 
} 

我怎樣才能減少這些額外的空間,以單一的空間,並降低所有選項卡(任意兩個詞之間),以一個空格。

例如:
在給這條線:

a b abb  ace ab 

它需要是:

a b abb ace ab 
+0

你試過了什麼?您發佈的小代碼有語法錯誤。 –

+0

我編輯它。現在可以了? – StackUser

+0

通常,我試圖使用'strtok',但我沒有成功達到這個問題的最終解決方案。 – StackUser

回答

1

這樣的:

#include <stdio.h> 

char *reduce_and_trim(char *s); 

int main(void) { 
    FILE *input_file = stdin; 
    char line[50]; 
    while (fgets(line,50, input_file) != NULL) { 
     printf("'%s'\n", reduce_and_trim(line)); 
    } 
    fclose(input_file); 
} 

#include <string.h> 

char *reduce_and_trim(char *s){ 
    static const char *whitespaces = " \t\n";//\t:tab, \n:newline, omit \f\r\v 
    size_t src = strspn(s, whitespaces);//Trim of the beginning 
    size_t des = 0;//destination 
    size_t spc = 0;//number of whitespaces 

    while(s[src] != '\0'){ 
     if((spc = strspn(s+src, whitespaces)) != 0){ 
      src += spc; 
      s[des++] = ' ';//reduce spaces 
     } else { 
      s[des++] = s[src++]; 
     } 
    } 
    if(des && s[des-1] == ' ') 
     s[des-1] = 0;//Trim of end 
    else 
     s[des] = 0; 

    return s; 
} 
+0

[DEMO](http://ideone.com/0FcuNP) – BLUEPIXY

1

這裏有一個簡單的解決方案:

char line[50]; 
while (fgets(line, sizeof line, input_file) != NULL) { 
    size_t i, j; 
    for (i = j = 0; line[i] != '\0'; i++) { 
     if (isspace((unsigned char)line[i])) { 
      while (isspace((unsigned char)line[++i])) 
       continue; 
      if (line[i] == '\0') 
       break; 
      if (j != 0) 
       line[j++] = ' '; 
     } 
     line[j++] = line[i]; 
    } 
    line[j] = '\0'; 
    printf("reduced input: |%s|\n", line); 
} 

現在,因爲這是家庭作業,這裏有一些額外的問題需要解決:

  • ,其中包括文件是必需的?
  • 爲什麼演員(unsigned char)line[i]需要?
  • 如果從input_file中讀取長度超過50個字節的行,會發生什麼情況?
  • 上一個問題出了什麼問題?
+0

@BLUEPIXY:謝謝!男孩,你的眼睛很銳利! – chqrlie

相關問題