来自像folder1/file1.txt这样的字符串的子字符串C
我有像“folder1/file1.txt”或“foldername1/hello.txt”这样的字符串,我需要使用包含斜杠(/)来标识文件夹名称的子字符串(例如:来自“folder1/file1.txt”)。 txt”我需要“folder1/”)。
文件夹名称的长度并不相同。 我怎样才能在C中做到这一点?谢谢
i have strings like "folder1/file1.txt" or "foldername1/hello.txt" and i need to take the substring that identify the folder name with the slash (/) included
(example: from "folder1/file1.txt" i need "folder1/").
The folders name are not all with the same length.
How can i do this in C?? thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
首先,使用 strchr: 找到斜杠的位置,
然后复制到合适的位置:
您确实应该编写一个函数来执行此操作,并且您需要决定如果 strchr() 返回 NULL(表明斜杠不存在)该怎么办。
First, find the position of the slash with strchr:
then copy into a suitable place:
You should really write a function to do this, and you need to decide what to do if strchr() returns NULL, indicating the slash is not there.
找到最后一个“/”字符,前进一个字符,然后截断字符串。假设该字符串是可修改的,并且由
char *filename;
指向:Find the last '/' character, advance one character then truncate the string. Assuming that the string is modifiable, and is pointed to by
char *filename;
:您可以使用 strstr() 函数:
You could use the strstr() function:
如果您在 POSIX 计算机上工作,则可以查找
dirname( )
函数,它或多或少可以满足您的需求。有一些特殊情况,它处理的是朴素代码所不处理的 - 但也要注意标准中的狡猾的话(关于修改输入字符串,可能返回一个指向输入字符串的指针,或者可能返回一个指向可以修改的静态内存的指针)之后)。它 (dirname()) 不会保留您所说的所需的尾部斜杠。然而,这很少是一个实际问题。在目录名和文件之间添加斜杠并不难。
If you work on a POSIX machine, you can look up the
dirname()
function, which does more or less what you want. There are some special cases that it deals with that naïve code does not - but beware the weasel words in the standard too (about modifying the input string and maybe returning a pointer to the input string or maybe a pointer to static memory that can be modified later).It (dirname()) does not keep the trailing slash that you say you require. However, that is seldom a practical problem; adding a slash between a directory name and the file is not hard.