是否有相当于在C#中的Scanner类字符串? [英] Is there an equivalent to the Scanner class in C# for strings?

查看:215
本文介绍了是否有相当于在C#中的Scanner类字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,我可以通过一个扫描仪字符串,然后我可以这样做, scanner.hasNext() scanner.nextInt好用的东西( ) scanner.nextDouble()等。

In Java I can pass a Scanner a string and then I can do handy things like, scanner.hasNext() or scanner.nextInt(), scanner.nextDouble() etc.

这使得一些pretty干净code解析包含数字的行字符串。

This allows some pretty clean code for parsing a string that contains rows of numbers.

这是如何在C#中的土地怎么办?

How is this done in C# land?

如果您有一个说有一个字符串:

If you had a string that say had:

"0 0 1 22 39 0 0 1 2 33 33"

在Java中我会传递到扫描仪,并做了

In Java I would pass that to a scanner and do a

while(scanner.hasNext()) 
    myArray[i++] = scanner.nextInt();

或者非常类似的东西。什么是C#这样做上下的方法是什么?

Or something very similar. What is the C#' ish way to do this?

推荐答案

我要添加为一个单独的答案,因为它是从我已经给出了答案截然不同。这里是你如何可以开始创建自己的扫描仪类:

I'm going to add this as a separate answer because it's quite distinct from the answer I already gave. Here's how you could start creating your own Scanner class:

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#中的Scanner类字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆