Say we have a string, called source. It contains “New York City – 12A – 1234B”
Here are the rules:
a. We know that the closest two numbers to the beginning of the string should kept, along with the following character and placed into a separate string, called results;
b. We are not certain if this following character will be a number or a letter
c. The formatting of the string itself varies – it could be “NY 12A 1234B”
d. We could care less about anything else!
Now I in my infinite wisdom have crafted this monstrosity. It works but please tell me there is a better way to do this or at best a cleaner, more performance conscious way of doing it.
class Program
{
public static int i = 0;
public static int q = 0;
public static int x = 0;
public static string source = "New York City - 12A - 1234B";
public static string results = "";
public static char[] from_source_char;
public static List<string> from_source_list = new List<string>();
static void Main(string[] args)
{
from_source_char = source.ToCharArray();
foreach (char unit in from_source_char)
{
from_source_list.Add(unit.ToString());
}
Console.WriteLine("Doing while " + i.ToString() + " < " + (from_source_list.Count() - 1).ToString());
while (i < from_source_list.Count() - 1)
{
Console.WriteLine("i is at " + i.ToString());
Console.WriteLine("Examining " + from_source_list[i].ToString());
try
{
q = Convert.ToInt32(from_source_list[i]);
results += from_source_list[i].ToString();
Console.WriteLine("Found part 1!");
x++;
}
catch
{
Console.WriteLine("Disregarding " + from_source_list[i].ToString());
// do nothing
}
if (x == 2)
{
Console.WriteLine("Found final part! " + from_source_char[i+1].ToString());
results += from_source_char[i+1].ToString();
break;
}
i++;
}
Console.WriteLine("Result is " + results.ToString());
Thread.Sleep(999999);
}
}
You could use a
Regexwith this pattern:@"^.*?(?<numbers>\d{2}\w).*$".Example: