New Snippet New Snippet Recent Snippets Recent Snippets My Snippets My Snippets Web Code Search Snippets Search
Sign inor Register
Language: C#

Strip Indentation from a String

99 Views
Copy Code Show/Hide Line Numbers
/// <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();
}
by Rick Strahl
  July 06, 2009 @ 11:03pm
Tags:
Comment:
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 Elijah Manor    July 08, 2009 @ 7:14am

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

return regularExpression.Replace(code, string.Empty);
}

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.

Add a comment


Report Abuse
brought to you by:
West Wind Techologies


If you find this site useful and use it frequently please consider making a donation to support this free service.
Donate