如何从字符数组中去除换行符
How to strip newlines from a char-array?
>我使用这个函数将文件的内容放在一个字符数组中:
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;
}
}
相关文章:
- 如何防止clang格式在流运算符调用之间添加换行符<<
- C/C++ - 查询平台相关的换行符(用于内存映射文件)
- 在 Stream C++ 文本之前有一个额外的换行符
- 流:CSV 文件中的换行符
- 如何在三元条件运算符中添加换行符和连接? :在 C++ 中
- Clang-格式:在多行语句之后的换行符上打开大括号
- 在输出流中插入换行符
- 防止控制台在通道字符(在 c++ 中)中输入空格(即空格、制表符和换行符)
- QProcess::readAllStandardOutput() 和换行符
- 如果有换行符,clang 格式不会附加大括号
- 提取后返回换行符的C++istream.get()
- 删除字符串数组中的换行符
- 如何检查字符串数组是否在C++中具有换行符
- 如何从字符数组中去除换行符
- 为什么 fstream::tellg() 返回值会因输入文本文件中的换行符数而增大,当文件针对 Windows (r
- 如何在C++中将空格和换行符分隔的整数读取到2D数组中
- CSV 文件转换为带换行符的 2D 数组 CPP
- 在字符数组中插入新的换行符
- 在无符号字符数组中读取充满字符串(用换行符分隔)的文件(反之亦然)的最快方法是什么?
- 用换行符结束数组输入