I have a string in this format: "ABC_123_"
I want to end up with and integer variable that is just the number portion of the string. What is the most efficient way to accomplish that in C#?
I have a string in this format: "ABC_123_"
I want to end up with and integer variable that is just the number portion of the string. What is the most efficient way to accomplish that in C#?
This should be efficient enough. Don't sweat if it's not the most efficient unless profiling tells you that it's a bottleneck of your application:
string s = "ABC_123_";
int i = Int32.Parse(s.Split('_')[1]);
Without more information about your problem, this is what I would go with.
If your string input will always be in the same form of ABC_123_ then this will work
int i = Int32.Parse("ABC_123_".Substring(4, 3));
If the lenght of your string etc. are fixed, you can use String.Substring.
The more complicated your string gets, the more you should use Regex.
Here's one way. I don't know about "most efficient", but it should work:
int? GetJustIntPart(string original)
{
var split = original.Split('_');
int test;
foreach (var item in split)
{
if (int.TryParse(item, out test))
return test;
}
return null;
}
Mandatory RegEx example to match all numbers in a string:
int num = Convert.ToInt32(Regex.Match("ABC_123_", @"\d+").Value);
Change to make sure it's surrounded by _:
int num = Convert.ToInt32(Regex.Match("ABC_123_", @"(?<=_)\d+(?=_)").Value);
Note: Value may be null/empty if your input string is in an improper format, so use int.TryParse or try/catch etc.