What would be the best way and more idiomatic to break a string into two at the place of the last dot? Basically separating the extension from the rest of a path in a file path or URL. So far what I'm doing is Split(".") and then String.Join(".") of everything but the last part. Sounds like using a bazooka to kill flies.
To split a string on the last occurrence of a substring:, use the lastIndexOf() method to get the last index of the substring and call the slice() method on the string to get the portions before and after the substring you want to split on.
Remove method can be used to remove last characters from a string in C#. The String. Remove method in C# creates and returns a new string after removing a number of characters from an existing string.
Split(String[], Int32, StringSplitOptions) Method This method is used to splits a string into a maximum number of substrings based on the strings in an array. You can specify whether the substrings include empty array elements. Syntax: public String[] Split(String[] separator, int count, StringSplitOptions options);
Split() method with params char[] ; Returns a string array that contains the substrings in this instance that are delimited by elements of a specified Unicode character array.
To get the path without the extension, use
System.IO.Path.GetFileNameWithoutExtension(fileName)
and to get the extenstion (including the dot), use
Path.GetExtension(fileName)
EDIT:
Unfortunately GetFileNameWithoutExtension strips off the leading path, so instead you could use:
if (path == null)
{
return null;
}
int length = path.LastIndexOf('.');
if (length == -1)
{
return path;
}
return path.Substring(0, length);
You could use Path.GetFilenameWithoutExtension()
or if that won't work for you:
int idx = filename.LastIndexOf('.');
if (idx >= 0)
filename = filename.Substring(0,idx);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With