如何从字符数组中去除换行符

How to strip newlines from a char-array?

本文关键字:换行符 数组 字符      更新时间:2023-10-16

>我使用这个函数将文件的内容放在一个字符数组中:

void Read::readFile(){
FILE * fp = fopen(this->filename,"rt");
fseek(fp, 0, SEEK_END);
long size = ftell(fp);
fseek(fp, 0, SEEK_SET);
char *pData = new char[size + 1];
fread(pData, sizeof(char), size, fp);
fclose(fp);
this->data = pData;
}

现在我想从字符数组中删除所有行尾。如何在不先将字符数组转换为字符串的情况下执行此操作?

这是家庭作业的一部分,我们不允许使用字符串库。

#include <algorithm>
size = std::remove(pData, pData + size, 'n') - pData;
pData[size] = 0; // optional

对于一些 C++11 lambda 的乐趣:

#include <algorithm>
size = std::remove_if(pData, pData + size, [](char c) { return c == 'n'; }) - pData;
pData[size] = 0; // optional

最简单的方法是使第二个缓冲区的大小与原始数组相同。

int len = size;
char* newBufer = calloc(len,sizeof(char));
int i = 0;
int j = 0;
int nlCount = 0;
for(i=0; i<len; i++) {
  if(pData[i] != 'n') {
    newBuffer[j++] = pData[i];
  } else {
    nlCount++;
  }
}
printf("Finished copying array without newlines. Total newlines removed: %d",nlCount);

这里的另一个好处是,由于您调用而不是错误地分配数组,所有值最初都是零,因此在这种情况下,一旦完成复制,(len-nlCount(到(len(的数据都将为零(即:"\0"(,因此它会自动以null结尾,就像字符串一样。完成后不要忘记释放((数组。

就地移除:

void strip_newlines(char* p) {
    char* q = p;
    while (p != 0 && *p != '') {
        if (*p == 'n') {
            p++;
            *q = *p;
        } 
        else {
            *q++ = *p++;
        }
    }
    *q = '';
}

像这样:

void Read::readFile()
{ 
    FILE * fp = fopen(this->filename,"rt"); 
    if (fp)
    {
        char *pData = NULL;
        fseek(fp, 0, SEEK_END); 
        long size = ftell(fp); 
        if (size != -1L)
        {
            pData = new char[size];
            if (size > 0)
            {
                fseek(fp, 0, SEEK_SET); 
                size = fread(pData, sizeof(char), size, fp);
            }
        }
        fclose(fp);
        if (size < 0)
        {
            delete[] pData;
            pData = NULL;
        }
        else if (size > 0)
        {
            char *start = pData;
            char *end = start + size;
            char *ptr = (char*) memchr(pData, 'n', size);
            while (ptr)
            {
                int len = 1;
                if ((ptr > start) && ((*ptr-1) == 'r'))
                {
                    --ptr;
                    ++len;
                }
                memmove(ptr, ptr+len, end - (ptr+len));
                end -= len;
                ptr = (char*) memchr(ptr, 'n', end - ptr);
            }
            size = (end - start);
        }
        this->data = pData; 
        this->size = size; 
    }
}