我写了一个通用方法,它将与 String
或 StringBuilder
参数一起使用。它返回参数中第二个单词的位置(单词可以用空格和换行符分隔)。对于使用参数的 []
和 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;
}
附注:我不能只为字符串参数编写一个函数并从StringBuilder.ToString()中调用它,因为我的StringBuilder可能非常大。