【问题标题】:How to do remove the last occurrence of a string from another string?如何从另一个字符串中删除最后一次出现的字符串?
【发布时间】:2011-12-19 06:36:15
【问题描述】:

假设我必须从另一个字符串中删除一个字符串的 最后一次出现。我该怎么办?

详细来说,我在 c 字符串中有一个文件名(gchar* 或 char*)

C:\SomeDir\SomeFolder\MyFile.pdf

我想删除扩展名 .pdf ,并将其更改为其他内容,例如 .txt 或 .png 。什么是最不麻烦但高效,方便和跨平台的方法?谢谢。

注意:我知道这在 C++ 中是一件非常简单的事情,但对于这个项目,我绝对必须使用 C 而不是其他语言。 (学历要求)

注意2:虽然你可以推荐其他第三方库,但我目前只能访问C标准库和GLib。

注意 3:我用“C”标签搜索过类似的问题,但似乎找不到。

【问题讨论】:

  • 扩展是否总是 3 个字符长(你的例子表明)并且它们总是在路径的末尾?你的源字符串是什么编码的?如果它是常规的 ASCII,你可以这样做 memcpy(source[strlen(source) - 4 /* count for \0 */], new_ext /* 3 chars + \0*/, 4);
  • @RedX 对于我的程序,文件名将作为命令行参数输入,因此我不确定扩展名的大小。例如,如果有人传递 *.aspx 文件怎么办?是的,字符串是 ASCII 格式,扩展名总是在路径的末尾。
  • 然后我会说反向搜索字符串的最后一个点,从输入的长度中减去它并创建一个具有正确扩展名的新字符串。

标签: c string glib standard-library


【解决方案1】:

看看basename。

NAME
dirname, basename - Parse pathname components

SYNOPSIS
#include <libgen.h>

char *dirname(char *path);
char *basename(char *path);

DESCRIPTION
Warning: there are two different functions basename() - see below.
The functions dirname() and basename() break a null-terminated
pathname string into directory and filename components. In the
usual case, dirname() returns the string up to, but not including,
the final ’/’, and basename() returns the component following the
final ’/’. Trailing ’/’ characters are not counted as part of the
pathname.

【讨论】:

  • 将您的代码缩进四个空格(或突出显示它并按“代码”格式化按钮),以便它像代码一样格式化。此外,您可以通过 Google 搜索并粘贴指向联机帮助页的链接,这比直接从联机帮助页复制和粘贴数据要容易得多(而且看起来更美观),但是这两种操作都不是一个很好的答案。
【解决方案2】:

只需用“strrchr”函数修改上面的“strtok”代码

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define MAX_PATH 255

int main() 
{
  char f[MAX_PATH] = "dir\\file.pdf";
  char f1[MAX_PATH];
  char ext[] = ".tmp";
  char *ptr = NULL;
  // find the last occurance of '.' to replace
  ptr = strrchr(f, '.');
  // continue to change only if there is a match found
  if (ptr != NULL) {
    snprintf(f1, (ptr-f)+1, "%s", f);
    strcat(f1, ext);
  }
  printf("%s\n", f1);
  return 1;
}

【讨论】:

    【解决方案3】:
    char fil[] = "C:\\SomeDir\\SomeFolder\\MyFile.pdf";
    char fil2[1000];
    char extension[] = ".tmp";
    
    // search for . and add new extension
    sprintf(fil2, "%s%s", strtok(fil, "."), extension);
    printf("%s\n", fil2);
    

    【讨论】:

      【解决方案4】:

      我通常会使用“splitpath”函数来分隔完整路径名的所有四个部分(dir、path、name、ext)。 最好的祝福 奥利弗

      【讨论】:

        猜你喜欢
        • 2012-06-05
        • 2012-05-31
        • 2016-05-27
        • 1970-01-01
        • 2012-04-14
        • 2021-12-11
        • 2011-11-18
        • 2014-03-04
        • 2014-06-13
        相关资源
        最近更新 更多