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.
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);
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.
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);
}
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);
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);
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.
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.
You can use string's method
LastIndexOf and substring to acomplish the task.