Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Java How to Read Data From a String (stringstream equivalent)

Let’s say I have a String (call it s) with the following format:

[String] [String] [double] [int]

for example,
"YES james 3.5 2"
I would like to read this data into separate variables (a String, a String, a double, and an int)

Note that I come from a C++ background. In C++, I would do something like the following:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

std::istringstream iss{s};   // create a stream to the string

std::string first, second; 
double third = 0.0;
int fourth = 0;
iss >> first >> second >> third >> fourth;  // read data

In Java, I came up with the following code:

String[] sa = s.split(" ");
        
String first = sa[0], second = sa[1];
double third = Double.parseDouble(sa[2]);
int fourth = Integer.parseInt(sa[3]);

However, I will have to do this to many different inputs, so I would like to use the most efficient and fastest way of doing this.

Questions:

  • Is there any better way to parse a string in Java, especially if I don’t need the first input?

>Solution :

Try it like this. Scanner’s constructor can take a string as a data source.

Scanner scan = new Scanner("12 34 55 88");
while (scan.hasNext()) {
   System.out.println(scan.nextInt());  
}

prints

12
34
55
88
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading