Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to break a string on the last dot on C#

Tags:

string

c#

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.

like image 376
pupeno Avatar asked Jul 06 '09 09:07

pupeno


People also ask

How do you split the last character of a string?

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.

How can I remove last character from a string in C#?

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.

How split a string after a specific character in C#?

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);

How do you break a string between?

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.


2 Answers

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);
like image 50
Patrick McDonald Avatar answered Oct 05 '22 18:10

Patrick McDonald


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);
like image 24
Philippe Leybaert Avatar answered Oct 05 '22 18:10

Philippe Leybaert