Java 是否具有等效的 StringStream?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37714339/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 02:42:36  来源:igfitidea点击:

Does Java have an StringStream equivalent?

java

提问by SomeStudent

So I am trying to get back into Java after doing C++ for quite some time, I decided to practice by rewriting my C++ programs into Java. Now in my Min Max Program I have the following lines of code:

所以我在做 C++ 一段时间后试图重新回到 Java,我决定通过将我的 C++ 程序重写为 Java 来练习。现在在我的 Min Max 程序中,我有以下几行代码:

  //C++ Code Sample
  getline(cin,mystr);
  stringstream(mystr) >> value;

  max = value;
  min = value;

  stringstream stream(mystr);

      while(stream >> value)
      {
        if(value > max)
        {
          max = value;
        }
        else if(value < min)
        {
          min = value;
        }
      }

Now, getline is equivalent to using the Scanner class, but what of the StringStream? While searching I saw people mentioning InputStream, but that seems to be related to reading from a file, ex: http://www.tutorialspoint.com/java/io/inputstream_read.htm.

现在,getline 相当于使用 Scanner 类,但是 StringStream 呢?在搜索时,我看到有人提到 InputStream,但这似乎与从文件中读取有关,例如:http: //www.tutorialspoint.com/java/io/inputstream_read.htm

Thus, I was wondering if I can get similar functionality? I could of course also ask the user to specify how many inputs they wish to type in, and then just populate an array; but that seems awkward.

因此,我想知道我是否可以获得类似的功能?我当然也可以要求用户指定他们希望输入的输入数量,然后填充一个数组;但这似乎很尴尬。

Update:

更新:

I created a quick work around that works as follows:

我创建了一个快速解决方法,其工作方式如下:

  String in = "";

            while(true)
            {

                in = input.nextLine();
                if(in.equalsIgnoreCase("DONE"))
                {
                    break;
                }
                value = Integer.parseInt(in);

                if(value > max)
                {
                    max = value;
                }
                else if(value < min)
                {
                    min = value;
                }
            }

回答by D.Shawley

You can use java.util.Scannerto parse a Stringusing Scanner(String). You can also use java.lang.StringBuilderto construct strings in an efficient manner.

您可以使用java.util.Scanner来解析Stringusing Scanner(String)。您还可以使用java.lang.StringBuilder以高效的方式构造字符串。