Ответ 1
Как насчет расширения строки? Обновление: я перечитал ваш вопрос, и я надеюсь, что есть лучший ответ. Это то, что меня тоже задевает, и решить его, как показано ниже, вызывает разочарование, но с плюсом он работает.
using System.Text.RegularExpressions;
namespace ConsoleApplication1
{
public static class StringExtensions
{
public static string StripLeadingWhitespace(this string s)
{
Regex r = new Regex(@"^\s+", RegexOptions.Multiline);
return r.Replace(s, string.Empty);
}
}
}
И пример консольной программы:
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string x = @"This is a test
of the emergency
broadcasting system.";
Console.WriteLine(x);
Console.WriteLine();
Console.WriteLine("---");
Console.WriteLine();
Console.WriteLine(x.StripLeadingWhitespace());
Console.ReadKey();
}
}
}
И вывод:
This is a test
of the emergency
broadcasting system.
---
This is a test
of the emergency
broadcasting system.
И более чистый способ использовать его, если вы решите пойти по этому маршруту:
string x = @"This is a test
of the emergency
broadcasting system.".StripLeadingWhitespace();
// consider renaming extension to say TrimIndent() or similar if used this way