Как насчет расширения строки?Обновление: я перечитал ваш вопрос и надеюсь, что есть лучший ответ.Это то, что меня тоже беспокоит, и необходимость его решения, как показано ниже, разочаровывает, но, с другой стороны, он работает.
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