# others - C# - 我的int'LastTwoChars'返回"StartIndex cannot be less than zero."异常

``````
static void Main(string[] args)

{

try

{

// Sample data - inputs 3 ints.

Console.WriteLine(Solution1(6, 1, 1));

Console.WriteLine(Solution1(1, 3, 1));

Console.WriteLine(Solution1(0, 1, 8));

Console.WriteLine(Solution1(5, 2, 4));

}

catch (Exception e)

{

Console.WriteLine(e.Message);

}

}

static string Solution1(int A, int B, int C)

{

string a ="a"; // a/b/c are added to string diverse when needed.

string b ="b";

string c ="c";

string diverse ="";

int totalLength = A + B + C; // Length of all 3 arrays

for(int i = 1; i <= totalLength; i++)

{

if (A >= B && A >= C && A > 0) { diverse = diverse + a; A = A - 1; }

if (B >= A && B >= C && B > 0) { diverse = diverse + b; B = B - 1; }

if (C >= A && C >= B && C > 0) { diverse = diverse + c; C = C - 1; }

}

return diverse;

}

``````

``````
static string Solution1(int A, int B, int C)

{

string a ="a"; // a/b/c are added to string diverse when needed.

string b ="b";

string c ="c";

string diverse ="";

int totalLength = A + B + C; // Length of all 3 arrays

for (int i = 1; i <= totalLength; i++)

{

// Finds the last 2 characters in the diverse string.

int LastTwoChars = diverse.Length - 2;

string twoCharCheck = diverse.Substring(LastTwoChars, 2);

if (A > 0 && B < 2 && C < 2 && twoCharCheck !="aa")

{

diverse = diverse + a; A = A - 1;

}

if (B > 0 && A < 2 && C < 2 && twoCharCheck !="bb")

{

diverse = diverse + b; B = B - 1;

}

if (C > 0 && B < 2 && A < 2 && twoCharCheck !="cc")

{

diverse = diverse + c; C = C - 1;

}

}

return diverse;

}

``````

``````
int LastTwoChars = diverse.Length - 2;

string twoCharCheck = LastTwoChars >= 0 ? diverse.Substring(LastTwoChars, 2) : string.Empty; // identical with if (LastTwoChars >= 0) twoCharCheck = diverse.Substring(LastTwoChars, 2); else twoCharCheck = string.Empty

if (A > 0 && B < 2 && C < 2 && (LastTwoChars < 0 || twoCharCheck !="aa")) // check the end only if you have at least 2 chars;

{

...

}

....

``````

``````
// returns the last two chars in a string format, or a default user string

private static string LastTwoCharsOrDefault(string input, string default)

{

var lastTwoCharsIdx = input.Length - 2;

if (lastTwoCharsIdx > 0 )

{

return input.Substring(lastTwoCharsIdx, 2);

}

// we don't have at least 2 chars, so lets just return the default

return default;

}

``````

``````

if (A > 0 && B < 2 && C < 2 && string.Equals("aa", LastTwoCharsOrDefault(diverse,"aa"), StringComparison.OrdinalIgnoreCase))

...

``````

`string diverse ="";`

``````
LastTwoChars is going to be -2 the first time through the loop.

``````