You can even solve this with a single line (albeit a bit ugly):
String.Join(String.Empty, input.Split('-').Select(q => (q.Length == 0 ? String.Empty : (q.Length > 1 ? (q.First() + q.Last()).ToString() : q.First().ToString())))).Substring(((input[0] + input[1]).ToString().Contains('-') ? 0 : 1), input.Length - ((input[0] + input[1]).ToString().Contains('-') ? 0 : 1) - ((input[input.Length - 1] + input[input.Length - 2]).ToString().Contains('-') ? 0 : 1));
first it splits the string into an array on each '-'
, then it combines only the first and last characters of each string (or only a single character, if there is only one, and leaves an empty string if there is nothing there), and then it combines the resulting enumerated string . Finally, we separate the first and last letters if they are not in the required range.
I know this is ugly, I just say that it is possible ..
It's probably best to just use simple
new Regex(@"\w(?=-)|(?<=-)\w", RegexOptions.Compiled)
and then work with it.
EDIT @ Cyril Polishchuk was faster .. his solution should work.
EDIT 2
After the question has been updated, here is a snippet that should do the trick:
string input = "ABC"; string s2; string s3 = ""; string s4 = ""; var splitted = input.Split('-'); foreach(string s in splitted) { if (s.Length == 0) s2 = String.Empty; else if (s.Length > 1) s2 = (s.First() + s.Last()).ToString(); else s2 = s.First().ToString(); s3 += s4 + s2; s4 = " and "; } int beginning; int end; if (input.Length > 1) { if ((input[0] + input[1]).ToString().Contains('-')) beginning = 0; else beginning = 1; if ((input[input.Length - 1] + input[input.Length - 2]).ToString().Contains('-')) end = 0; else end = 1; } else { if ((input[0]).ToString().Contains('-')) beginning = 0; else beginning = 1; if ((input[input.Length - 1]).ToString().Contains('-')) end = 0; else end = 1; } string result = s3.Substring(beginning, s3.Length - beginning - end);
It's not very elegant, but it should work (not tested, though ..). it works almost the same as the single line above ...
source share