String
またはStringBuilder
引数で使用される汎用メソッドを作成します。引数の 2 番目の単語の位置を返します (単語はスペースと改行で区切ることができます)。引数の使用については[]
、Length()
以下の醜いコードよりも優れたものを発明できませんでした。それを行うよりエレガントな方法はありますか?
int PositionOfTheSecondWord<T>(T text) // T can be String or StringBuilder
{
int pos = 0;
int state = 0;
char c;
// Get length of the text
// UGLY!
int length = text is StringBuilder ? (text as StringBuilder).Length : (text as String).Length;
while (pos <= length - 1)
{
// Get the next character
// UGLY!
c = text is StringBuilder ? (text as StringBuilder)[pos] : (text as String)[pos];
if (c == ' ' || c == '\n') // space
{
if (state == 1)
state = 2; // 2 means the space between the first and the second word has begun
}
else // a letter
if (state == 0)
state = 1; // 1 means the first word has begun
if (state == 2)
return pos;
pos++;
}
return -1;
}
PS StringBuilder が巨大になる可能性があるため、String 引数の関数を作成して StringBuilder.ToString() から呼び出すことはできません。