如果我有一个字符串说“abc.txt”,有没有一个快速的方法来获得一个子字符串,这只是“abc”?
我不能做一个fileName.IndexOf('.'),因为文件名可以是“abc.123.txt”或其他东西,我显然只是想摆脱扩展名(即。“abc.123”)。
如果我有一个字符串说“abc.txt”,有没有一个快速的方法来获得一个子字符串,这只是“abc”?
我不能做一个fileName.IndexOf('.'),因为文件名可以是“abc.123.txt”或其他东西,我显然只是想摆脱扩展名(即。“abc.123”)。
当前回答
这个实现应该可以工作。
string file = "abc.txt";
string fileNoExtension = file.Replace(".txt", "");
其他回答
如果你想使用字符串操作,那么你可以使用lastIndexOf()函数,它搜索字符或子字符串的最后一次出现。Java有很多字符串函数。
ReadOnlySpan<char> filename = "abc.def.ghi.txt";
var fileNameWithoutExtension = RemoveFileExtension(filename); //abc.def.ghi
string RemoveFileExtension(ReadOnlySpan<char> path)
{
var lastPeriod = path.LastIndexOf('.');
return (lastPeriod < 0 ? path : path[..lastPeriod]).ToString();
}
的路径。GetFileNameWithoutExtension方法提供了作为参数传递的文件名,但没有扩展名,从名称可以明显看出这一点。
这个实现应该可以工作。
string file = "abc.txt";
string fileNoExtension = file.Replace(".txt", "");
/// <summary>
/// Get the extension from the given filename
/// </summary>
/// <param name="fileName">the given filename ie:abc.123.txt</param>
/// <returns>the extension ie:txt</returns>
public static string GetFileExtension(this string fileName)
{
string ext = string.Empty;
int fileExtPos = fileName.LastIndexOf(".", StringComparison.Ordinal);
if (fileExtPos >= 0)
ext = fileName.Substring(fileExtPos, fileName.Length - fileExtPos);
return ext;
}