Use a little LINQ and Regex to find the shortest indentation, then remove that number of characters from all lines.
string[] l_lines = {
" public class MyClass",
" {",
" private bool MyMethod(string s)",
" {",
" return s == \"\";",
" }",
" }"
};
int l_smallestIndentation =
l_lines.Min( s => Regex.Match( s, "^\\s*" ).Value.Length );
string[] l_result =
l_lines.Select( s => s.Substring( l_smallestIndentation ) )
.ToArray();
foreach ( string l_line in l_result )
Console.WriteLine( l_line );
Prints:
public class MyClass
{
private bool MyMethod(string s)
{
return s == "";
}
}
This program will scan all strings in the array. If you can assume that the first line is the least indented, then you could improve performance by scanning only the first line:
int l_smallestIndentation =
Regex.Match( l_lines[0], "^\\s*" ).Value.Length;
Also note that this will handle a tab character ("\t") as a single character. If there is a mix of tabs and spaces, then reversing the indent may be tricky. The easiest way to handle that would be to replace all instances of tabs with the appropriate number of spaces (often 4, though individual applications can vary wildly) before running the code above.
It would also be possible to modify the code above to give additional weight to tabs. At that point, the regex is no longer of much use.
string[] l_lines = {
"\t\t\tpublic class MyClass",
" {",
" private bool MyMethod(string s)",
" {",
" \t \t\treturn s == \"\";",
" }",
"\t\t\t}"
};
int l_tabWeight = 8;
int l_smallestIndentation =
l_lines.Min
(
s => s.ToCharArray()
.TakeWhile( c => Char.IsWhiteSpace( c ) )
.Select( c => c == '\t' ? l_tabWeight : 1 )
.Sum()
);
string[] l_result =
l_lines.Select
(
s =>
{
int l_whitespaceToRemove = l_smallestIndentation;
while ( l_whitespaceToRemove > 0 )
{
l_whitespaceToRemove -= s[0] == '\t' ? l_tabWeight : 1;
s = s.Substring( 1 );
}
return s;
}
).ToArray();
Prints (assuming your console window has a tab width of 8 like mine):
public class MyClass
{
private bool MyMethod(string s)
{
return s == "";
}
}
You may need to modify this code to work with edge-case scenarios, such as zero-length lines or lines containing only whitespaces.
UnindentAsMuchAsPossibleto "return"void, do you? - Tim Schmelter