如果我有一个字符串说“abc.txt”,有没有一个快速的方法来获得一个子字符串,这只是“abc”?

我不能做一个fileName.IndexOf('.'),因为文件名可以是“abc.123.txt”或其他东西,我显然只是想摆脱扩展名(即。“abc.123”)。


当前回答

这个实现应该可以工作。

string file = "abc.txt";
string fileNoExtension = file.Replace(".txt", "");

其他回答

字符串。LastIndexOf可以工作。

string fileName= "abc.123.txt";
int fileExtPos = fileName.LastIndexOf(".");
if (fileExtPos >= 0 )
 fileName= fileName.Substring(0, fileExtPos);

你可能不会问UWP api。 但是在UWP中,文件。DisplayName为不带扩展名的名称。希望对别人有用。

如果你想使用字符串操作,那么你可以使用lastIndexOf()函数,它搜索字符或子字符串的最后一次出现。Java有很多字符串函数。

    /// <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;
    }
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();
}