如何从C中的给定字符串中删除\n或\ t?

goe*_*goe 8 c string

如何在C中删除所有\n和\ t的字符串?

Eva*_*ran 15

这适用于我快速而肮脏的测试.是否到位:

#include <stdio.h>

void strip(char *s) {
    char *p2 = s;
    while(*s != '\0') {
        if(*s != '\t' && *s != '\n') {
            *p2++ = *s++;
        } else {
            ++s;
        }
    }
    *p2 = '\0';
}

int main() {
    char buf[] = "this\t is\n a\t test\n test";
    strip(buf);
    printf("%s\n", buf);
}
Run Code Online (Sandbox Code Playgroud)

为了安抚Chris,这里有一个版本,它将首先复制并返回它(因此它将在文字上工作).你需要malloc结果.

char *strip_copy(const char *s) {
    char *p = malloc(strlen(s) + 1);
    if(p) {
        char *p2 = p;
        while(*s != '\0') {
            if(*s != '\t' && *s != '\n') {
                *p2++ = *s++;
            } else {
                ++s;
            }
        }
        *p2 = '\0';
    }
    return p;
}
Run Code Online (Sandbox Code Playgroud)


Eda*_*aor 5

如果你想用其他东西替换 \n 或 \t,你可以使用函数 strstr()。它返回一个指向具有特定字符串的函数中第一个位置的指针。例如:

// Find the first "\n".
char new_char = 't';
char* pFirstN = strstr(szMyString, "\n");
*pFirstN = new_char;
Run Code Online (Sandbox Code Playgroud)

您可以在循环中运行它以查找所有 \n 和 \t。

如果你想“剥离”它们,即从字符串中删除它们,你实际上需要使用与上面相同的方法,但是每次找到\n或\t时都复制字符串“back”的内容,所以“这是一个测试”变成了:“这是一个测试”。

您可以使用 memmove(不是 memcpy,因为 src 和 dst 指向重叠内存),如下所示:

char* temp = strstr(str, "\t");
// Remove \n.
while ((temp = strstr(str, "\n")) != NULL) {
// Len is the length of the string, from the ampersand \n, including the \n.
     int len = strlen(str);
 memmove(temp, temp + 1, len); 
}
Run Code Online (Sandbox Code Playgroud)

您需要再次重复此循环以删除 \t。

注意:这两种方法都可以就地工作。这可能不安全!(阅读 Evan Teran 的评论以了解详细信息。此外,这些方法效率不高,尽管它们确实为某些代码使用了库函数,而不是滚动您自己的。