[ACCEPTED]-Best way to break a string on the last dot on C#-string
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);
0
You could use Path.GetFilenameWithoutExtension()
or if that won't work for 1 you:
int idx = filename.LastIndexOf('.');
if (idx >= 0)
filename = filename.Substring(0,idx);
To get the path without the extension, use
System.IO.Path.GetFileNameWithoutExtension(fileName)
and 3 to get the extenstion (including the dot), use
Path.GetExtension(fileName)
EDIT:
Unfortunately 2 GetFileNameWithoutExtension strips off the 1 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);
The string method LastIndexOf maybe of some use to 3 you here.
But the Path or FileInfo operators 2 will be better suited for filename based 1 operations.
I think what you're really looking for is 1 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);
}
What about using the LastIndexOf method 3 which returns the last found position of 2 a character. Then you can use Substring 1 to extract what you want.
String.LastIndexOf will return you the position 3 of the dot if it ever exists in the string. You 2 can then String.Substring methods to split 1 the string.
You can use string's method
LastIndexOf and 1 substring to acomplish the task.
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.