Language: C#
Strip Indentation from a String
/// <summary> /// Strips a string of any leading whitespace that exists /// for all lines of the string. /// </summary> /// <param name="code"></param> /// <returns></returns> public static string StripIndentation(string code) { // normalize tabs to 3 spaces string text = code.Replace("\t", " "); string[] lines = text.Split(new string[3] { "\r\n", "\r", "\n" }, StringSplitOptions.None); // keep track of the smallest indent int minPadding = 1000; foreach (var line in lines) { if (line.Length == 0) // ignore blank lines continue; char[] chars = line.ToCharArray(); int count = 0; foreach (char chr in chars) { if (chr == ' ' && count < minPadding) count++; else break; } if (count == 0) return code; minPadding = count; } string strip = new String(' ', minPadding); StringBuilder sb = new StringBuilder(); foreach (var line in lines) { sb.AppendLine(StringUtils.ReplaceStringInstance(line, strip, "", 1, false)); } return sb.ToString(); }
Tags:
Description:
This code works but is really tedious. Wonder if there's a better way to strip indentation. Code basically loops through string and finds common white space characters for all lines, then strips them.
by Scott Isaacs
July 08, 2009 @ 8:09am
It looks like the original code will still preserve indenting structure, but will just "normalize" it so that at least one line is left justified. The comment above will remove all leading whitespace from each line, causing all lines to be left justified.
Report Abuse
Subscribe
Discuss
What's new
What is it
New Snippet
Recent Snippets
My Snippets
Web Code
Search


public static string StripIndentation(string code)
{
var regularExpression = new Regex(@"^[\s]+", RegexOptions.Multiline);
return regularExpression.Replace(code, string.Empty);
}