(如果你正在尋找如何將製表符轉換爲空格在編輯器中,看到我的回答結束)
幾乎8歲的問題,但我最近需要用空格替換標籤。
該解決方案替換選項卡高達 4或8個空格。
邏輯通過輸入字符串迭代一次一個字符,並跟蹤輸出字符串中的當前位置(列#)。
- 如果遇到
\t
(選項卡字符) - 查找下一個製表位,計算需要多少空間才能到下一個製表位,替換\噸,這些數量的空格。
- 如果
\n
(換行) - 將它追加到輸出字符串並將新位置上的位置指針重置爲1。 Windows上的新行是\r\n
,在UNIX(或風格)上使用\n
,所以我想這應該適用於這兩個平臺。我在Windows上進行了測試,但沒有UNIX方便。
- 任何其他字符 - 將其追加到輸出字符串並增加位置。
。
using System.Text;
namespace CSharpScratchPad
{
class TabToSpaceConvertor
{
static int GetNearestTabStop(int currentPosition, int tabLength)
{
// if already at the tab stop, jump to the next tab stop.
if ((currentPosition % tabLength) == 1)
currentPosition += tabLength;
else
{
// if in the middle of two tab stops, move forward to the nearest.
for (int i = 0; i < tabLength; i++, currentPosition++)
if ((currentPosition % tabLength) == 1)
break;
}
return currentPosition;
}
public static string Process(string input, int tabLength)
{
if (string.IsNullOrEmpty(input))
return input;
StringBuilder output = new StringBuilder();
int positionInOutput = 1;
foreach (var c in input)
{
switch (c)
{
case '\t':
int spacesToAdd = GetNearestTabStop(positionInOutput, tabLength) - positionInOutput;
output.Append(new string(' ', spacesToAdd));
positionInOutput += spacesToAdd;
break;
case '\n':
output.Append(c);
positionInOutput = 1;
break;
default:
output.Append(c);
positionInOutput++;
break;
}
}
return output.ToString();
}
}
}
調用代碼會像
string input = "I\tlove\tYosemite\tNational\tPark\t\t,\t\t\tGrand Canyon,\n\t\tand\tZion";
string output = CSharpScratchPad.TabToSpaceConvertor.Process(input, 4);
輸出字符串將獲得價值
I love Yosemite National Park , Grand Canyon,
and Zion
如何轉換選項卡,空格在編輯器?
如果你偶然發現這個問題,因爲你無法找到選項將選項卡轉換爲編輯器中的空格(就像我曾經想過編寫自己的工具一樣),這裏是選項的位置不同的編輯器 -
Notepad++: Edit > Blank Operations > TAB to Space
Visual Studio: Edit > Advanced > Untabify Selected Lines
SQL Management Studio: Edit > Advanced > Untabify Selected Lines
這裏有些答案是不知道標籤的概念停止(請參閱http ://www.gnu.org/software/emacs/manual/html_node/emacs/Tab-Stops.html和http://www.jwz.org/doc/tabs-vs-spaces.html)。 @ckal,Nick-McCowin和user275640是正確的答案。 – Jonke 2013-11-14 08:24:35
@Jonke發佈了一個新的解決方案,以最多4或8個空格正確確定製表符。 – HappyTown 2017-01-31 17:00:50