如何获取字符串中的子字符串并将其存储在另一个字符串中
How to get substring inside string and store it in another string
我有两个相等的字符串,我需要删除其中一个的一部分,然后将其存储在另一个中。
我的代码不工作:
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;
}
这是预期的输出:
./imgtools mysuperimage.img
mysuperimage.img
mysuperimage
这是实际输出:
./imgtools mysuperimage.img
mysuperimage
mysuperimage
我该如何解决这个问题?
您需要复制 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 '[=10=]', just null terminate the string, it's simpler
else
puts("Extension not found");
// Print strings
puts (imagefile);
puts (argv[1]);
return 0;
}
我有两个相等的字符串,我需要删除其中一个的一部分,然后将其存储在另一个中。
我的代码不工作:
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;
}
这是预期的输出:
./imgtools mysuperimage.img
mysuperimage.img
mysuperimage
这是实际输出:
./imgtools mysuperimage.img
mysuperimage
mysuperimage
我该如何解决这个问题?
您需要复制 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 '[=10=]', just null terminate the string, it's simpler
else
puts("Extension not found");
// Print strings
puts (imagefile);
puts (argv[1]);
return 0;
}