【问题标题】:removing trailing and leading spaces from a file从文件中删除尾随和前导空格
【发布时间】:2019-12-09 22:41:16
【问题描述】:

我正在尝试从长度未知的文本文件中读取行。 在该行中,可以有前导和尾随空格,直到字符串出现。 所以我的第一步是逐行读取并为字符串分配内存。然后删除所有前导和尾随空格。 之后,我想检查字符串中是否包含任何无效字符的空白字符。例如,字符串不能看起来像这样"bad string",但可以像这样"goodstring"。 但是,当我调用该函数来删除前导和尾随空格时,它也会删除空格之前或之后的字符。

谁能告诉我我做错了什么?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define NCHAR 64

char *readline (FILE *fp, char **buffer);
char *strstrip(char *s);


int main (int argc, char **argv) {

    char *line = NULL;
    size_t idx = 0;
    FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin;
    if (!fp) {
        fprintf (stderr, "error: file open failed '%s'.\n", argv[1]);
        return 1;
    }

    while (readline (fp, &line)) {  /* read each line in 'fp' */
        printf (" line[%2zu] : %s\n", idx++, line);
        free (line);
        line = NULL;
    }
    if (fp != stdin) fclose (fp);

    return  0;
}

/* read line from 'fp' allocate *buffer NCHAR in size
 * realloc as necessary. Returns a pointer to *buffer
 * on success, NULL otherwise.
 */
char *readline (FILE *fp, char **buffer) 
{
    int ch;
    size_t buflen = 0, nchar = NCHAR;
    size_t n;
    char *invalid_character = " ";

    *buffer = malloc (nchar);    /* allocate buffer nchar in length */
    if (!*buffer) {
        fprintf (stderr, "readline() error: virtual memory exhausted.\n");
        return NULL;
    }

    while ((ch = fgetc(fp)) != '\n' && ch != EOF) 
    {
        (*buffer)[buflen++] = ch;

        if (buflen + 1 >= nchar) {  /* realloc */
            char *tmp = realloc (*buffer, nchar * 2);
            if (!tmp) {
                fprintf (stderr, "error: realloc failed, "
                                "returning partial buffer.\n");
                (*buffer)[buflen] = 0;
                return *buffer;
            }
            *buffer = tmp;
            nchar *= 2;
        }
        strstrip(*buffer); //remove traiing/leading spaces
    }
    (*buffer)[buflen] = 0;           /* nul-terminate */


   if (invalid_character[n = strspn(invalid_character, *buffer)] == '\0') //check if a string has invalid character ' ' in it
    {
        puts(" invalid characters");

    } 

    if (buflen == 0 && ch == EOF) {  /* return NULL if nothing read */
        free (*buffer);
        *buffer = NULL;
    }

    return *buffer;
}
char *strstrip(char *s)
{
    size_t size;
    char *end;

    size = strlen(s);

    if (!size)
        return s;

    end = s + size - 1;
    while (end >= s && isspace(*end))
        end--;
    *(end + 1) = '\0';

    while (*s && isspace(*s))
        s++;

    return s;
}

【问题讨论】:

  • 这里发生了什么或应该发生什么:invalid_character[n = strspn(invalid_character, buffer[i])] == '\0' 和 i 在那里做什么?你想在字符串中找一个空格,如果找到就输出" valid characters"?请说明当输入“不能像这样的字符串”时会发生什么。
  • 我不明白为什么每次读取字符时都在循环中调用 strstrip,因为该函数假定字符串为空终止,但在调用它时您还没有这样做.您也不要使用 strstrip 的返回值来指示新字符串的开始(但是,您不能简单地将 *buffer 替换为它,因为那时您的 free 将不起作用)。
  • @KamilCuk 如果字符串是这样输入的“坏字符串”,那么它将打印出无效字符,否则什么都没有
  • @EdmCoff 我不明白你说我无法释放分配的内存是什么意思
  • 将char 传递给isspace 有未定义行为的风险,因为参数的类型为int,并且必须在0 到UCHAR_MAX 的范围内,否则EOF。接受的答案不能解决这个问题。

标签: c string malloc whitespace


【解决方案1】:

您无需担心传递给strstrip() 的字符串的长度,只需遍历字符串中的所有字符即可删除空格字符,例如以下版本从 s 中删除 ALL 空格:

/** remove ALL leading, interleaved and trailing whitespace, in place.
 *  the original start address is preserved but due to reindexing,
 *  the contents of the original are not preserved. returns pointer
 *  to 's'. (ctype.h required)
 */
char *strstrip (char *s)
{
    if (!s) return NULL;                     /* valdiate string not NULL */
    if (!*s) return s;                       /* handle empty string */

    char *p = s, *wp = s;                    /* pointer and write-pointer */

    while (*p) {                             /* loop over each character */
        while (isspace ((unsigned char)*p))  /* if whitespace advance ptr */
            p++;
        *wp++ = *p;                          /* use non-ws char */
        if (*p)
            p++;
    }
    *wp = 0;    /* nul-terminate */

    return s;
}

(注意:如果isspace() 的参数是char 类型,则需要转换为unsigned char,请参见注意部分,例如man 3 isalpha )

仅删除多余的空格

以下版本删除了前导和尾随空格并将多个空格序列折叠为一个空格:

/** remove excess leading, interleaved and trailing whitespace, in place.
 *  the original start address is preserved but due to reindexing,
 *  the contents of the original are not preserved. returns pointer
 *  to 's'. (ctype.h required) NOTE: LATEST
 */
char *strstrip (char *s)
{
    if (!s) return NULL;                        /* valdiate string not NULL */
    if (!*s) return s;                               /* handle empty string */

    char *p = s, *wp = s;                      /* pointer and write-pointer */

    while (*p) {
        if (isspace((unsigned char)*p)) {                    /* test for ws */
            if (wp > s)                         /* ignore leading ws, while */
                *wp++ = *p;                   /* preserving 1 between words */
            while (*p && isspace (unsigned char)(*p))    /* skip remainder  */
                p++;
            if (!*p)                               /* bail on end-of-string */
                break;
        }
        if (*p == '.')                 /* handle space between word and '.' */
            while (wp > s && isspace ((unsigned char)*(wp - 1)))
                wp--;
        *wp++ = *p;                                      /* use non-ws char */
        p++;
    }
    while (wp > s && isspace ((unsigned char)*(wp - 1))) /* trim trailing ws */
        wp--;
    *wp = 0;    /* nul-terminate */

    return s;
}

(注意: s 必须是可变的,因此不能是字符串文字)

【讨论】:

  • 谢谢。这是您的第一个未经编辑的答案完全符合我的要求。如果字符串中有空格,您编辑的答案不会打印出“无效字符”
  • 第一个答案删除了所有 excess 空格删除前导,压缩多个交错,并删除尾随空格。此版本删除了 All 空格。我会重新发布原件。
  • 你知道——我已经有一段时间没有看到那个了。如果wp 在被推进之前指向最后一个非空白,那么就没有必要了,但我记得它是为一个极端情况而写的(你可能指出:) 我会再传一遍通过。
  • @chux-ReinstateMonica 它可以从第一个完全删除(没有特殊情况)。在第二个 /* handle space between word and '.' */ 的情况下," hello world ." 需要在以 '.' 结尾的句子之前不留空格 第二个中的 /* trim trailing ws */ 是由于循环的因式分解,*wp++ = *p; 可能包括一个如果前面的字符是 '.' 后跟 " \0",则尾随 space。 if {..} if {..} 可能会被重构为 if {..} else if {..} ... else {..} 并消除它们。
  • @Kaz - 你是 100% 正确的。在上面使用isspace(c) 的所有地方,如果c 是char 而不是unsigned char,则从技术上讲它应该是isspace ((unsigned char)(c))。谢谢你指出这一点。 (你看到它被忽略了很多次)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-08-20
  • 2017-04-30
  • 2016-10-14
  • 1970-01-01
  • 2012-02-28
  • 1970-01-01
  • 2018-10-04
相关资源
最近更新 更多