我正在应用程序的脚本引擎中工作,想从针尖开始进行一些字符串裁剪。现在的目的是从完整路径中提取文件夹位置,但是我也可以想到其他用途:
data / some_folder / some_item.txt 到 data / some_folder
脚本环境或多或少是“ C lite”,并且对字符串的支持有限:
值得注意的是,没有可用的 strinlast ,所以我只是自己破解了。
它工作正常,但是我不禁以为我缺少了什么,并且有比我所使用的更好的技术。字符串限制为256个字符,因此搜索将始终很小。任何建议表示赞赏。
char temp_string;
int index;
// Get string length.
index = strlength(haystack);
// There's no working strinlast function, so we'll just
// build our own naive search algorithm here.
//
// We create a temporary string from haystack, starting
// at the far right character. We then use stringinfirst
// to see if our needle is in the temp_string, and if it
// is we now have an index to use for strleft.
//
// If the result is invalid (-1), then we build the
// tempstring from haystack, now one character back, and
// continue until our strinfirst gets a good result.
do
{
index--;
// Get the right end of haystack, starting
// from index.
temp_string = strright(haystack, index);
} while (strinfirst(temp_string, needle) == -1);
// Now that we have our index pointing to the last
// occurrence of needle in haystack, we can use strleft
// to return the preceding characters.
return strleft(haystack, index);