我有一个看起来像这样的输入字符串:
4 Bob 32 Joe 64 Sue 123 Bill 42
其中 4 表示后面的字符串整数对的数量。我目前的处理方式如下所示:
var strings = input.Split(' ');
int count = Int32.Parse(strings[0]);
for ( int i = 0; i < count; i++ )
{
string name = strings[count*2 + 1];
int number = Int32.Parse(strings[count*2 + 1]);
ProcessPerson(name, number);
}
这个感觉挺麻烦的。 C# 中是否有一些库可以包装字符串并为我提供诸如“readInt”和“readString”之类的服务。我最终想要这样的东西:
int count = input.ReadInt();
for(int i = 0; i<count; i++)
{
ProcessPerson(input.ReadString(), input.ReadInt());
}
在这种情况下看起来并没有太大的改进,但我的实际对象模型有点复杂。我知道其他语言也有类似的功能,但我不记得有任何 .net 库可以简单地从字符串的前面读取。
最佳答案
您可以轻松地自己编写这样一个“库”:
class Parser
{
private readonly Queue<string> m_parts;
public Parser(string s)
{
m_parts = new Queue<string>(s.Split(' '));
}
public string ReadString()
{
return m_parts.Dequeue();
}
public int ReadInt32()
{
return int.Parse(ReadString());
}
}
如果字符串可能很大,或者您正在从流中读取它,则必须自己进行拆分:
class StreamParser
{
private readonly TextReader m_reader;
public StreamParser(string s)
: this(new StringReader(s))
{}
public StreamParser(TextReader reader)
{
m_reader = reader;
}
public string ReadString()
{
var result = new StringBuilder();
int c = m_reader.Read();
while (c != -1 && (char)c != ' ')
{
result.Append((char)c);
c = m_reader.Read();
}
if (result.Length > 0)
return result.ToString();
return null;
}
public int ReadInt32()
{
return int.Parse(ReadString());
}
}
关于c# - 从字符串前面读取单个 int 的最简单方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6418505/