c#标签包装字符串

问题描述:

我正在写出一个大字符串(大约100行)到一个文本文件,并希望整个文本块选项卡。c#标签包装字符串

WriteToOutput("\t" + strErrorOutput); 

我上面使用的这行只是标签文本的第一行。我怎样才能缩进/选项卡的整个字符串?

更换由换行符所有换行符后按Tab:

WriteToOutput("\t" + strErrorOutput.Replace("\n", "\n\t")); 
+0

谢谢......有没有一种方法可以让字符串太长而不能放在一行上,也可以选项卡?现在,所有新行都是标签,但是其中一些较长的行正在环绕而没有任何缩进 – sammis

+0

请查看此[包装字符串扩展方法的片段](http://bryan.reynoldslive.com/post/Wrapping -string-data.aspx),它返回一个字符串列表 – jltrem

你可以让你的字符串输出与CRLF + TAB代替CRLF的副本。并写入要输出的字符串(仍以前面的TAB为前缀)。

strErrorOutput = strErrorOutput.Replace("\r\n", "\r\n\t"); 
WriteToOutput("\t" + strErrorOutput); 

File.WriteAllLines(FILEPATH,input.Split(new string[] {"\n","\r"}, StringSplitOptions.None) 
           .Select(x=>"\t"+x)); 

要做到这一点,你就必须有一个有限的线路长度(即< 100个字符)在这一点这个问题变得容易。

public string ConvertToBlock(string text, int lineLength) 
{ 
    string output = "\t"; 

    int currentLineLength = 0; 
    for (int index = 0; index < text.Length; index++) 
    { 
     if (currentLineLength < lineLength) 
     { 
      output += text[index]; 
      currentLineLength++; 
     } 
     else 
     { 
      if (index != text.Length - 1) 
      { 
       if (text[index + 1] != ' ') 
       { 
        int reverse = 0; 
        while (text[index - reverse] != ' ') 
        { 
         output.Remove(index - reverse - 1, 1); 
         reverse++; 
        } 
        index -= reverse; 
        output += "\n\t"; 
        currentLineLength = 0; 
       } 
      } 
     } 
    } 
    return output; 
} 

这将任何文本转换成的文本块被分成长度lineLength的线和所有开始与标签并以换行符结束。