替换c字符串中的最后一个单词

时间:2015-08-04 07:21:44

标签: c arrays string

这完全是针对c编程语言的。

我刚才解决了这个问题,但由于一些数据丢失,我不得不重写代码。

我使用cmake构建程序,它使用在运行时确定的相对路径来获取当前bin目录。

当我在运行时获取bin位置时,它通常返回如下内容:

/Users/username/FOLDER/project/build/bin/Debug/
/Users/username/Library/Caches/cmake/gen/ad053ed7/Debug/bin/
/Users/username/FOLDER/project/build/bin/

正如您所看到的,这些名称都非常相似但略有不同。通过在第二个到最后一个尾部斜杠后删除字符串并将其替换为文件夹名称,可以找到我想要访问的文件:

/Users/username/FOLDER/project/build/bin/folderName/
/Users/username/Library/Caches/cmake/gen/ad053ed7/Debug/folderName/
/Users/username/FOLDER/project/build/folderName/

现在我正在努力让这个问题再次解决。

如何在C中执行类似的操作,以便在这些和将来可能的位置使用?

修改

char *base_path = getBasePath(); //returns a string to current executable dir

// printf("%s \ n",base_path);

size_t len = strlen(base_path);
char* tmp = (char*)malloc(sizeof(char) * (len * 2)); //malloc a large chunk of space just for now

memcpy(tmp, base_path, len);
tmp[len-1] = '\0';

//printf("tmp:\t%s\n",tmp);

const char sep = '/'; //possible separator conflicts on other platforms

size_t max = 0;
size_t slen = 0;
for(size_t i = 0; i < len; i++)
{
    if(tmp[i] == sep)
    {
        max = i;
        //printf("%c",tmp[i]);
    }
    if(tmp[i] == '\0')
    {
        slen = i;
        printf("len is:%zu\n",i);
    }
}
//printf("%c, %zu\n",tmp[max], max);
memcpy(tmp + max, "/resources/", 11);

tmp[slen + 7] = '\0';
const size_t flen = slen + 7;
realloc(tmp, slen+7);
printf("tmp:\t%s\n",tmp);

res_dir = (char*)malloc(sizeof(char) * flen); //res dir is static char*
memcpy(res_dir, tmp, flen);
res_dir[flen] = '\0'; 

// printf(&#34; res dir:\ t%s \ n&#34;,res_dir);

free(base_path);

2 个答案:

答案 0 :(得分:1)

char *myfile = "folder/file.txt";
char *last_slash = strrchr(s, '/'); // reverse find from end
char *last_word = &last_slash[1]; // next character after

printf ("'%s' this is the last word", last_word);

"'file.txt' is the last word"

看起来你想要替换最后一个单词......

    myfile[last_slash - myfile + 1] = 0; // null terminate after the last slash by setting character after slash to 0
    char newstring[1024] = {0};
    char *replace_with = "this_new_file.txt"
    sprintf (newstring, "%s%s", myfile, replace_with);

    printf ("Result '%s'", newstring);

"Result 'folder/this_new_file.txt'"

进行了几次快速编辑。

答案 1 :(得分:0)

首先反转字符串。 然后使用strtok()函数,你可以删除你想要的确切字符串。 再次反转确切的字符串。

相关问题