我剛剛寫了這個方法,我想知道如果類似的東西已經存在於框架中?它只是看起來像這些方法之一...獲得領先的空白
如果不是,有沒有更好的方法來做到這一點?
/// <summary>
/// Return the whitespace at the start of a line.
/// </summary>
/// <param name="trimToLowerTab">Round the number of spaces down to the nearest multiple of 4.</param>
public string GetLeadingWhitespace(string line, bool trimToLowerTab = true)
{
int whitespace = 0;
foreach (char ch in line)
{
if (ch != ' ') break;
++whitespace;
}
if (trimToLowerTab)
whitespace -= whitespace % 4;
return "".PadLeft(whitespace);
}
感謝
編輯: 讀了一些評論,它清楚,我還需要處理的標籤後。
,因爲網站空間修剪下降到只有一個,但我會努力,我不能給出一個很好的例子:
說出輸入與5位的字符串,該方法將返回與4串空間。如果輸入少於4個空格,則返回""
。 這可能有所幫助:
input spaces | output spaces
0 | 0
1 | 0
2 | 0
3 | 0
4 | 4
5 | 4
6 | 4
7 | 4
8 | 8
9 | 8
...
你可以給一些樣本輸入/輸出嗎?目前還不完全清楚你想從你的代碼中做什麼。例如,如果第一個字符不是空白和'trimToLowerTab == false',則'whitespace == 0'。因此,無論線的長度如何,總是以「return」「.PadLeft(0)」結尾。如果第二個字符不是空格,則總是以1個空格結束,等等。我沒有看到這些情況下舍入的位置。多一點上下文也會有幫助。 – 2010-10-11 15:59:54
所以如果我給字符串''e「'(想象3個空格),那麼方法返回的字符串應該是」「,因爲只有3個空格。但是,如果輸入字符串是「e」(5個空格),則返回的字符串將是'「」'(4個空格)(在空間總數之下的最接近4的倍數)。如果參數是錯誤的,那麼前導空格只是在沒有任何修改的情況下給出。編輯:網站從評論中刪除空白... – Nobody 2010-10-11 16:03:17
你能編輯你的問題,並把你的例子作爲代碼嗎?我在您的評論中看不到超過一個連續的空間。 – 2010-10-11 16:05:48