Pablo Fernandez
Pablo Fernandez

Reputation: 287750

Best way to break a string on the last dot on 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.

Upvotes: 14

Views: 20986

Answers (9)

Patrick McDonald
Patrick McDonald

Reputation: 65451

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

Upvotes: 3

Ratnesh Maurya
Ratnesh Maurya

Reputation: 706

You can use string's method

LastIndexOf and substring to acomplish the task.

Upvotes: 1

sharptooth
sharptooth

Reputation: 170529

String.LastIndexOf will return you the position of the dot if it ever exists in the string. You can then String.Substring methods to split the string.

Upvotes: 1

Mark
Mark

Reputation: 2432

What about using the LastIndexOf method which returns the last found position of a character. Then you can use Substring to extract what you want.

Upvotes: 1

Marc Gravell
Marc Gravell

Reputation: 1063824

If you want performance, something like:

    string s = "a.b.c.d";
    int i = s.LastIndexOf('.');
    string lhs = i < 0 ? s : s.Substring(0,i),
        rhs = i < 0 ? "" : s.Substring(i+1);

Upvotes: 28

Aamir
Aamir

Reputation: 15576

Path.GetExtension() should help you.

Upvotes: 1

Markus Olsson
Markus Olsson

Reputation: 22580

I think what you're really looking for is Path.GetFileNameWithoutExtension Method (System.IO) but just for the heck of it:

string input = "foo.bar.foobar";
int lastDotPosition = input.LastIndexOf('.');

if (lastDotPosition == -1)
{
    Console.WriteLine("No dot found");
}
else if (lastDotPosition == input.Length - 1)
{
    Console.WriteLine("Last dot found at the very end");

}
else
{
    string firstPart = input.Substring(0, lastDotPosition);
    string lastPart = input.Substring(lastDotPosition + 1);

    Console.WriteLine(firstPart);
    Console.WriteLine(lastPart);
}

Upvotes: 1

Wayne
Wayne

Reputation: 3435

The string method LastIndexOf maybe of some use to you here.

But the Path or FileInfo operators will be better suited for filename based operations.

Upvotes: 2

Philippe Leybaert
Philippe Leybaert

Reputation: 171864

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

Upvotes: 10

Related Questions