2011-11-01 73 views
1

说我必须从另一个字符串中删除最后发生的字符串。我会怎么做呢?如何从另一个字符串中删除最后一次出现的字符串?

为了详细说明,我在AC的字符串的文件名(gchar *或字符*)

C:\ SomeDir \ SomeFolder \ MyFile.pdf

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

:我知道这是一个非常简单的事情,在C++中,但这个项目做,我绝对必须使用C和任何其他语言。 (学术要求)

注2::虽然你可以建议其他的第三方库,我目前只可以访问C标准库和GLib的。

注3:我已经寻找与“C”标记类似的问题,但似乎无法找到任何。

+0

将扩展永远是3个charachters足够长(例如指示),将他们永远是在路径的尽头?什么编码是你的源字符串?如果它的常规ASCII可以执行'memcpy(source [strlen(source) - 4/* count for \ 0 * /],new_ext/* 3 chars + \ 0 * /,4);' – RedX

+0

@RedX对于我的程序,文件名将作为命令行参数输入,所以我不确定扩展名的大小。例如,如果有人传递* .aspx文件?是的,字符串是ASCII码,扩展名总是在路径的末尾。 – ApprenticeHacker

+0

然后我会说反向搜索最后一个点的字符串,从输入的长度中减去该字符串,并创建一个具有正确扩展名的新字符串。 – RedX

回答

1
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); 
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. 
+0

将代码缩进四个空格(或突出显示并按下“代码”格式化按钮),使其格式化为代码。此外,您可以Google和粘贴到手册页的链接比直接从联机帮助页复制和粘贴数据更容易(和更好看),但这两种操作都无法提供非常好的答案。 –

1

我通常会使用“splitpath”函数来分隔完整路径名(dir,path,name,ext)的全部四个部分。 最好的问候 奥利弗

1

只需修改与“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; 
} 
相关问题