字符串扩展如何?更新:我重读你的问题,我希望有更好的答案。这也是让我感到困惑的事情,因为下面的解决方案令人沮丧,但它的确有用。
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
你可以举个例子!? – gideon
我通常所做的就是在自己的行上(即'@'之前的换行符)开始字符串,所以至少它不在右边,然后突然在左边。我知道这不是你想要的解决方案。 –
是的,我也经常这样做。这真的不是什么大事,但我认为这将是一个有趣的问题。 –