Get Substring - everything before certain char
I'm trying to figure out the best way to get everything before the - character in a string. Some example strings are below. The length of the string before - varies and can be any length
223232-1.jpg
443-2.jpg
34443553-5.jpg
so I need the value that's from the start index of 0 to right before -. So the substrings would turn out to be 223232, 443, and 34443553
.Net Fiddle example
class Program
{
static void Main(string[] args)
{
Console.WriteLine("223232-1.jpg".GetUntilOrEmpty());
Console.WriteLine("443-2.jpg".GetUntilOrEmpty());
Console.WriteLine("34443553-5.jpg".GetUntilOrEmpty());
Console.ReadKey();
}
}
static class Helper
{
public static string GetUntilOrEmpty(this string text, string stopAt = "-")
{
if (!String.IsNullOrWhiteSpace(text))
{
int charLocation = text.IndexOf(stopAt, StringComparison.Ordinal);
if (charLocation > 0)
{
return text.Substring(0, charLocation);
}
}
return String.Empty;
}
}
Results:
223232
443
34443553
344
34
Use the split function.
static void Main(string[] args)
{
string s = "223232-1.jpg";
Console.WriteLine(s.Split('-')[0]);
s = "443-2.jpg";
Console.WriteLine(s.Split('-')[0]);
s = "34443553-5.jpg";
Console.WriteLine(s.Split('-')[0]);
Console.ReadKey();
}
If your string doesn't have a -
then you'll get the whole string.
String str = "223232-1.jpg"
int index = str.IndexOf('-');
if(index > 0) {
return str.Substring(0, index)
}
Things have moved on a bit since this thread started.
Now, you could use
string.Concat(s.TakeWhile((c) => c != '-'));
One way to do this is to use String.Substring
together with String.IndexOf
:
int index = str.IndexOf('-');
string sub;
if (index >= 0)
{
sub = str.Substring(0, index);
}
else
{
sub = ... // handle strings without the dash
}
Starting at position 0, return all text up to, but not including, the dash.