当我们要parse什么东西的时候,常常会需要对自己的character stream或者token list实现一个Peek 函数。之前偶的实现都是多读一位,有的时候还要记一个偏移量。用来保证peek以后read不会受影响。最近看到一个Peek实现,很简单,很方便,不知道大家都是已经这样实现的。
主要思想就是添加一个cached value.
private
char
cachedChar;
public char Peek()
{
if (cachedChar == null )
{
cachedChar = RealRead();
}
return cachedChar;
}
public char Read()
{
char ret;
if (cachedChar != null )
{
ret = cachedChar;
cachedChar = null ;
} else
{
ret = RealRead();
}
return ret;
}
private char RealRead()
{
// your implementation
}
public char Peek()
{
if (cachedChar == null )
{
cachedChar = RealRead();
}
return cachedChar;
}
public char Read()
{
char ret;
if (cachedChar != null )
{
ret = cachedChar;
cachedChar = null ;
} else
{
ret = RealRead();
}
return ret;
}
private char RealRead()
{
// your implementation
}
希望对你有帮助