如何在换行符“\ n”之前将字符“\ t”添加到字符串中

时间:2015-10-06 01:26:14

标签: c newline fgets strcat

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

strcat(line_data, "\t");

但只是在换行符后面添加了标签

2 个答案:

答案 0 :(得分:4)

假设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';

答案 1 :(得分:0)

假设line_data不包含'\n',代码什么都不做:

你需要的只是

char *p = strchr(line_data, '\n');
if (p) strcpy(p, "\t\n");
相关问题