Home > Back-end >  How to get specific strings/int/double from text (java)
How to get specific strings/int/double from text (java)

Time:12-02

So I've got this program that needs to take in information from a text file and use it to generate data for weather data recording stations. One of the lines looks like this:

KE000063612 3.117   35.617  515 1/1/14  -1  87  98  73

the lines repeat for like 8700 lines with the same spacing, etc. how would I go about getting specific pieces of data? Like if I wanted to get the last three ints (in this case 87 98 and 73) for like four stations, or just the month of three different ones. I'm in java btw

I've tried using just the Column/line numbers but that's so inefficient that I really don't want to do that unless I absolutely have to.

CodePudding user response:

You could do something like this:

  1. Read the whole line then split them into a String array.

  2. When you want to use the values for computation you can just parse them to their proper types.

The code prints the 3 values on the far right of the string and prints its sum.

Scanner scanner = new Scanner(System.in);
String[] input = scanner.nextLine().split(" ");

System.out.println(input[6]   " "   input[7]   " "   input[8]);
System.out.print("sum: ");
System.out.println(Integer.parseInt(input[6])   Integer.parseInt(input[7])   Integer.parseInt(input[8]));

Note: Make sure that you have exactly a single space between the values, or you can remove empty values on the array.

Input:

KE000063612 3.117 35.617 515 1/1/14 -1 87 98 73

Output:

87 98 73
sum: 258

CodePudding user response:

You can create a method to parse the string as required.

String s = "KE000063612 3.117   35.617  515 1/1/14  -1  87  98  73";

// for the last three values
int[] results = getValues(s, "\\d \\s \\d \\s \\d $", "\\s ");
System.out.println(Arrays.toString(results));

// for the month, day, and year of date
results = getValues(s, "\\d /\\d /\\d ", "\\/");
System.out.println(Arrays.toString(results));

prints

[87, 98, 73]
[1, 1, 14]

The method takes:

  • the string to parse
  • the pattern to describe the portion to be parsed
  • the pattern to split that portion

It works as follows:

  • first the method streams the matches
  • then it splits them
  • converts to an int
  • and returns them in an array.
public static int[] getValues(String s, String pattern, String splitPat) {
    return Pattern.compile(pattern)
            .matcher(s)
            .results()
            .map(MatchResult::group)
            .flatMap(str -> Arrays.stream(str.split(splitPat)))
            .mapToInt(Integer::parseInt)
            .toArray();
}
  • Related