如何使用数组用C中的单个空格替换(多个)空白字符(空格,制表符,换行符)的所有实例?

时间:2019-09-18 10:17:01

标签: c algorithm array-algorithms

我尝试使用getchar()解决问题,并且可以正常工作,但是现在我正在使用fgets()逐行获取文本,并且整个文本存储在数组中。我想用一个空格替换多个空格字符的所有实例,包括空格,制表符和换行符。 这就是我使用getchar()所做的:

 int c;

while ((c = getchar ()) != EOF
{
    if (c == '\r') continue;
    if (c == '\n') {       
        putchar (c);
        while ((c = getchar ()) == '\n' || c == '\r') {}
        if (c != EOF) ungetc (c, stdin); else break;
        continue;
    }
    if (c == ' ' || c == '\t') {  
        putchar (' ');
        while ((c = getchar ()) == ' ' || c == '\t') {}
        if (c != EOF) ungetc(c, stdin); else break;
        continue;
    }
    putchar (c);
}
return 0;

}

现在,我正在尝试这样做:

while (1) {
    if (fgets(line,max_len, stdin) == NULL) break;
    for (int i=0;i<strlen(line);i++){
        text[n++]=line[i];
    }
}

每个文本在哪里存储在我要对其进行过滤的数组中。

1 个答案:

答案 0 :(得分:1)

  • 不要重复自己:您只需要一个getc()和一个putc()
  • 在循环中,您只需要记住先前输出的字符是否为空白即可。
  • breakcontinue存在是有原因的。

int count;

for(count=0; ; ) {
    int ch; 
    ch = getc(stdin);
    if( ch == EOF) break;
    switch(ch) {
    case ' ':
    case '\t':
    case '\n':
    case '\r':
            if(count++) continue;
            ch = ' ';
            break;
    default:
            count=0;
            break;
            }
    putc(ch, stdout);
    }

重写字符缓冲区的类似逻辑:


char line[100];
while ( fgets(line,sizeof line, stdin) ) {
    unsigned dst,src,count;  
    for (count=dst=src=0; line[dst]=line[src++];){
        switch(line[dst]) {
        case ' ':
        case '\t':
        case '\n':
        case '\r':
            if(count++) continue;
            line[dst++] = ' ';
            break;
        default:
            dst++;
            count=0;
            break;
            }
        }
    fputs(line,stdout);
    }

如您所见,您不需要缓冲区,它只会使事情复杂化。