Подключаем пространство имен
Код
using System.Text.RegularExpressions;
А вот метод:
Код
string SwapWords(string s) {
// разбиваем строку на слова
Regex regex = new Regex(@"\w+", RegexOptions.IgnoreCase);
MatchCollection matches = regex.Matches(s);
if (matches.Count > 0) {
// получаем первое
Match first = matches[0];
// и последнее
Match last = matches[matches.Count - 1];
// вытаскиваем символы до первого слова..
string header = s.Substring(0, first.Index);
// ...между словами...
int pos = first.Index + first.Length;
string middle = s.Substring(pos, last.Index - pos);
// ...и после последнего слова
pos = last.Index + last.Length;
string tail = s.Substring(pos, s.Length - pos);
// формируем результат
return header + last.Value + middle + first.Value + tail;
}
return s;
}