我当前正在使用 printf("'%.*s'\n", length, start);
打印字符串,其中 start
是 const char*
且长度为 int
。
打印的字符串有时包含换行符\n
,这会扰乱格式,是否可以将它们替换为字符\
和n打印输出中的
,而不是 \n
字符。
如果没有,你能帮忙提供一个替换字符的函数吗?
该字符串是一个 malloc 字符串,它具有来自不同指针的其他引用,因此无法更改。
编辑:我编写了以下代码,我认为它可以满足我的需要
static void printStr(const char* start, int length) {
char* buffer = malloc(length * sizeof(char));
int processedCount = 0;
for(int i = 0; i < length; i++) {
char c = start[i];
if(c == '\n') {
printf("%.*s\\n", processedCount, buffer);
processedCount = 0;
} else {
buffer[processedCount] = c;
processedCount++;
}
}
printf("%.*s", processedCount, buffer);
free(buffer);
}
最佳答案
不需要分配内存来处理字符串。简单地说,迭代原始字符并根据需要打印字符。例如:
#include <stdio.h>
void print(const char * str, int length)
{
for (int i = 0; i < length; ++i) {
if (str[i] == '\n') {
putchar('\\');
putchar('n');
} else
putchar(str[i]);
}
}
int main()
{
print("hello\nworld!", 12);
return 0;
}
关于c - 不使用 printf 打印新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50865373/