Вы могли бы написать функцию, как следующий один, что бы разделить строку на две секции по месту нахождения того, что вы искали (с помощью метода String.Split()
) для и это будет только удалить совпадения из второй секции (с использованием String.Replace()
):
public static string RemoveAllButFirst(string s, string stuffToRemove)
{
// Check if the stuff to replace exists and if not, return the original string
var locationOfStuff = s.IndexOf(stuffToRemove);
if (locationOfStuff < 0)
{
return s;
}
// Calculate where to pull the first string from and then replace the rest of the string
var splitLocation = locationOfStuff + stuffToRemove.Length;
return s.Substring(0, splitLocation) + (s.Substring(splitLocation)).Replace(stuffToRemove,"");
}
Вы могли бы просто назвать его с помощью:
var output = RemoveAllButFirst(input,",");
красивее подход действительно может включать создание метод расширения, который обрабатывается это немного более чисто:
public static class StringExtensions
{
public static string RemoveAllButFirst(this string s, string stuffToRemove)
{
// Check if the stuff to replace exists and if not, return the
// original string
var locationOfStuff = s.IndexOf(stuffToRemove);
if (locationOfStuff < 0)
{
return s;
}
// Calculate where to pull the first string from and then replace the rest of the string
var splitLocation = locationOfStuff + stuffToRemove.Length;
return s.Substring(0, splitLocation) + (s.Substring(splitLocation)).Replace(stuffToRemove,"");
}
}
, который будет вызываться через:
var output = input.RemoveAllButFirst(",");
Вы можете see a working example of it here.
Я назвал бы LINQ один довольно элегантный :) – Rawling
@Rawling: отредактировал мой ответ на комментарий, почему я не люблю его (даже если я люблю LINQ). –
Мне очень нравится ваш оператор LINQ, но я не понимаю побочных эффектов, которые вы упомянули еще. Что вы ожидаете там? –