我编写了一个通用方法,将与String
或StringBuilder
参数一起使用。它返回参数中第二个单词的位置(单词可以用空格和换行符分隔)。对于使用[]
andLength()
的论点,我想不出比下面丑陋的代码更好的东西了。有没有更优雅的方法来做到这一点?
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 我不能只为 String 参数编写一个函数并从 StringBuilder.ToString() 调用它,因为我的 StringBuilder 可能很大。