简体   繁体   English

如何获取字符串中的子字符串并将其存储在另一个字符串中

[英]How to get substring inside string and store it in another string

I have two equal strings, I need to delete a portion of one of them, and store it in another.我有两个相等的字符串,我需要删除其中一个的一部分,并将其存储在另一个中。

My code is not working:我的代码不起作用:

int main(int argc, char *argv[])
{
    char *imagetmp = argv[1];
    char *imagefile = imagetmp;
    char *unpackdir = imagetmp;

    // Remove substring from char imagefile
    char * pch;
    pch = strstr (imagefile,".img");
    strncpy (pch,"",6);

    // Print strings
    puts (imagefile);
    puts (unpackdir);
    return 0;
}

Here is the expected output:这是预期的输出:

./imgtools mysuperimage.img
mysuperimage.img
mysuperimage

Here is the actual output:这是实际输出:

./imgtools mysuperimage.img
mysuperimage
mysuperimage

How can I fix this?我怎样才能解决这个问题?

You will need to make a copy of argv[1] , if you have two pointers to the same string they will naturally print the same:您将需要复制argv[1] ,如果您有两个指向同一字符串的指针,它们自然会打印相同的内容:

int main(int argc, char *argv[])
{
    char imagefile[100];
    if(argc < 2) {
       puts("Too few arguments");
       return 1;
    }

    strncpy(imagefile, argv[1], sizeof(imagefile) - 1);
    //char *unpackdir = argv[1]; you can use argv[1] directly

    // Remove substring from char imagefile
    char * pch;
    if((pch = strstr (argv[1],".img")))
        *pch = 0; //or '\0', just null terminate the string, it's simpler 
    else
        puts("Extension not found");

    // Print strings
    puts (imagefile);
    puts (argv[1]);
    return 0;
}

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

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