简体   繁体   English

从C语言的指针char中删除String

[英]Remove String from pointer pointer char in C

I'm trying to remove a string from a pointer pointer char ( char **str ), my function removes the string and make duplicates of the remaining strings. 我试图从指针char( char **str )中删除一个字符串,我的函数删除了该字符串,并使其余字符串重复。

void    remove_dup(char **split, char *name)
{
    char **sp;
    sp = split;
    while (*sp != NULL)
    {
        if (strncmp(*sp, name, strlen(name)) == 0)
        {
            *sp = *(sp + 1);
            sp++;
        }
        else
            sp++;
    }
}

complete code 完整的代码

Skipping one string won't work. 跳过一个字符串是行不通的。 You need to keep track of read and unread strings. 您需要跟踪已读和未读的字符串。

This will remove duplicate entries 这将删除重复的条目

    void    remove_dup(char **split, char *name)
    {
        char **read,**write;
        read=write=split;
        char count=0;
        while (*read!=NULL){
            if (strncmp(*read, name, strlen(name)) == 0){
                if(count==0){
                    *(write++)=*(read++);   
                    count=1;
                }
                else{
                    //free string
                    read++;
                    continue;
                }
            }
            else
                *(write++)=*(read++);   
        }
        *write=0;
    }

If the duplicate entries are to be removed properly, strings must be freed properly. 如果要正确删除重复的条目,则必须正确释放字符串。 You should change the way you have initialized strings to be able to do that. 您应该更改初始化字符串的方式才能做到这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM