Home > front end >  Java How to Read Data From a String (stringstream equivalent)
Java How to Read Data From a String (stringstream equivalent)

Time:12-22

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:

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?

CodePudding user response:

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

CodePudding user response:

As it has been mentioned in the comments, if this is coming from keyboard (or really from an input stream) you could use Scanner class to do so. However, from input sources other than keyboard, I will not use Scanner but some other method to parse strings. For example, if reading lines from a file, you may want to use a Reader instead. For this answer, I will assume the input source is the keyboard.

Using Scanner to get the input

Scanner scanner = new Scanner(System.in);
System.out.print("Provide your input: ");
String input = scanner.nextLine();
input.close();

Break the String into tokens

Here you have a few options. One is to break down the string into substring by splitting the input using white space as a delimeter:

String[] words = input.split("\\s");

If the order of these substrings is guaranteed, you can assign them directly to the variables (not the most elegant solution - but readable)

String first = words[0];
String second = words[1];
double third = words[2];
int fourth = words[3];

Alternatively, you can extract the substrings directly by using String#substring(int) and/or String#substring(int, int) methods and test whether or not the obtained substring is a number (double or int), or just simply a string.

  • Related