简体   繁体   English

如何获得最后一笔?

[英]How to get the last strtok?

I want to split a "string" (delimiter \\ ) to get the last occurrence. 我想分割一个“字符串”(定界符\\ )以获取最后一次出现。 This is the code I wrote: 是我写的代码:

char str[] ="D:\\Google Drive\\My Files\\Test.zip";
char * buffer = str;

sprintf(buffer, "%s", strtok(str,"\\"));
cout << buffer;

but it returns D: instead of Test.zip (the first occurrence, not the last). 但它返回D:而不是Test.zip (第一次出现,而不是最后一次出现)。 How would you do this task? 您将如何执行此任务?

I need to use/keep sprintf (ie format string approch). 我需要使用/保持sprintf(即格式字符串方法)。

Use strrchr instead - it's more appropriate in this context, and both non-destructive and reentrant too: 请改用strrchr-在这种情况下更合适,并且非破坏性和可折返性也都适用:

char str[] ="D:\\Google Drive\\My Files\\Test.zip";
char * buffer = strrchr(str, '\\');
cout << buffer + 1;

If you really do have to keep the redundant and inefficient use of sprintf as per your question then you can of course do this: 如果确实需要根据您的问题保留sprintf的冗余和低效使用,那么您当然可以这样做:

char str[] ="D:\\Google Drive\\My Files\\Test.zip";
char buffer[256];
sprintf(buffer, "%s", strrchr(str, '\\') + 1);
cout << buffer;

LIVE DEMO 现场演示

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

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