我试图删除文件名.txt扩展名被写入字符串“垫”:分割字符串令牌
sscanf(mat, "%s.txt", ime_datoteke);
如果mat="sm04567890.txt"
我想那ime_datoteke="sm04567890"
。 正如在例子中我尝试使用sscanf
,但它不工作(它复制到ime_datoteke)。
我该如何在C中做到这一点?
我试图删除文件名.txt扩展名被写入字符串“垫”:分割字符串令牌
sscanf(mat, "%s.txt", ime_datoteke);
如果mat="sm04567890.txt"
我想那ime_datoteke="sm04567890"
。 正如在例子中我尝试使用sscanf
,但它不工作(它复制到ime_datoteke)。
我该如何在C中做到这一点?
您可以修改您的sscanf
方法稍微读一个字符串,不包括.
:
sscanf(mat, "%[^.].txt", ime_datoteke);
然而,这将是最好的,如果你看一下从字符串末尾的.
性格,然后复制由它确定的子字符串。
char* dot = strrchr(mat, '.');
strncpy(ime_datoteke, mat, dot - mat);
使用strrchr:
char* pch = strrchr(str,'.');
if(pch)
*pch = '\0';
此示例使用strrchr()
查找字符串中的最后一期,然后将复制preceeds那段字符串的唯一部分。
如果未找到句点,则会复制整个字符串。
const char *fullstop;
if ((fullstop = strrchr(mat, '.')))
strncpy(ime_datoteke, mat, fullstop - mat);
else
strcpy(ime_datoteke, mat);
与标准的C函数strstr
:
char a[] ="sm04567890.txt";
char *b = strstr(a, ".txt");
*b = '\0';
printf("%s\n", a);
会打印:
sm04567890