c - 如何在换行符 "\t"之前将字符 "\n"添加到字符串中

标签 c newline fgets strcat

我想知道如何取一行字符串并在换行符前添加一个制表符。现在我正在使用 fgets 获取行然后使用

strcat(line_data, "\t");

但这只是在换行符之后添加制表符

最佳答案

假设line_data有足够的内存:

char* newline = strchr(line_data, '\n');
newline[0] = '\t';
newline[1] = '\n';
newline[2] = '\0';

当然,如果没有,你必须做这样的事情:

size_t len = strlen(line_data);
char* newstr = malloc(len + 2); /* one for '\t', another for '\0' */
memcpy(newstr, line_data, len);
newstr[len - 1] = '\t'; /* assuming '\n' is at the very end of the string */
newstr[len] = '\n';
newstr[len + 1] = '\0';

关于c - 如何在换行符 "\t"之前将字符 "\n"添加到字符串中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32960313/

相关文章:

c++ - 如何在 C++ 中的输出文件中多行空格

c - 如何计算文件中的换行符,但不计算只是换行符的行?

c - Turbo C 数组问题

linux - 普通口齿不清 : run shell command containing the string "\n"

c - 优化此代码,使其代码运行时间小于 1s

java - printf 中 Java 的 "%n"是怎么回事?

c - 在 C : leading zeros 中读取文件

c - fgets 故障排除

c++ - 使用 C API 在 aspell 中创建自定义词典

c - c中char数组中的空格