在 Java 中,我可以向 Scanner 传递一个字符串,然后我可以做一些方便的事情,例如 scanner.hasNext()
或 scanner.nextInt()
、 scanner.nextDouble()
等
这允许一些非常干净的代码来解析包含数字行的字符串。
这是如何在 C# 领域完成的?
如果你有一个字符串说 had:
"0 0 1 22 39 0 0 1 2 33 33"
在 Java 中,我会将其传递给扫描仪并执行
while(scanner.hasNext())
myArray[i++] = scanner.nextInt();
或者非常相似的东西。这样做的 C# 方法是什么?
最佳答案
我将把它作为一个单独的答案添加,因为它与我已经给出的答案完全不同。以下是您可以开始创建自己的 Scanner 类的方法:
class Scanner : System.IO.StringReader
{
string currentWord;
public Scanner(string source) : base(source)
{
readNextWord();
}
private void readNextWord()
{
System.Text.StringBuilder sb = new StringBuilder();
char nextChar;
int next;
do
{
next = this.Read();
if (next < 0)
break;
nextChar = (char)next;
if (char.IsWhiteSpace(nextChar))
break;
sb.Append(nextChar);
} while (true);
while((this.Peek() >= 0) && (char.IsWhiteSpace((char)this.Peek())))
this.Read();
if (sb.Length > 0)
currentWord = sb.ToString();
else
currentWord = null;
}
public bool hasNextInt()
{
if (currentWord == null)
return false;
int dummy;
return int.TryParse(currentWord, out dummy);
}
public int nextInt()
{
try
{
return int.Parse(currentWord);
}
finally
{
readNextWord();
}
}
public bool hasNextDouble()
{
if (currentWord == null)
return false;
double dummy;
return double.TryParse(currentWord, out dummy);
}
public double nextDouble()
{
try
{
return double.Parse(currentWord);
}
finally
{
readNextWord();
}
}
public bool hasNext()
{
return currentWord != null;
}
}
关于c# - 是否有与 C# 中的 Scanner 类等效的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/722270/