Java: parsing a string - java

I have a series of strings, each of the format :
"{3.242, 87611}, {5.658, 7.3731}, {5.547, 8.7631} ......"
Each pair of numbers in curly brackets represents one Latitude/Longitude point (and each number is of type double).
I want to parse the string so that each point in the string is represented as a separate Lat/Lon object, that I store in a list of points.
I am pretty new to Java (and parsing). I have been looking at a lot of examples but I'm still really confused as to how to even begin.
How do I go about doing this?

You can use regExp to fetch points first,
String str = "{3.242, 87611},{5.658, 7.3731}";
Pattern pattern = Pattern.compile("\\{(.*?)\\}");
Matcher match = pattern.matcher(str);
while(match.find()) {
System.out.println(match.group(1));
}
OUTPUT
3.242, 87611
5.658, 7.3731
Now you can just use split to find two points and you can parse them to Double. Note here (.*?) is a group which means any String

Assuming you have already have this String in some variable str, you can split str into it's component numbers
String[] splitNumbers = str.split("[{}, ]+");
then iterate over this list and use each pair of numbers to construct a Coordinate object.
Coordinate[] coords = new Coordinate[splitNumbers.length/2];
for(int i=0; i < splitNumbers.length-2;i+=2){
double longitude = Double.paresDouble(splitNumbers[i]);
double latitude = Double.paresDoublesplitNUmbers[i+1]);
coords[i/2] = new Coordinate(longitude,latitude);
}

Related

Extracting digits in the middle of a string using delimiters

String ccToken = "";
String result = "ssl_transaction_type=CCGETTOKENssl_result=0ssl_token=4366738602809990ssl_card_number=41**********9990ssl_token_response=SUCCESS";
String[] elavonResponse = result.split("=|ssl");
for (String t : elavonResponse) {
System.out.println(t);
}
ccToken = (elavonResponse[6]);
System.out.println(ccToken);
I want to be able to grab a specific part of a string and store it in a variable. The way I'm currently doing it, is by splitting the string and then storing the value of the cell into my variable. Is there a way to specify that I want to store the digits after "ssl_token="?
I want my code to be able to obtain the value of ssl_token without having to worry about changes in the string that are not related to the token since I wont have control over the string. I have searched online but I can't find answers for my specific problem or I maybe using the wrong words for searching.
You can use replaceAll with this regex .*ssl_token=(\\d+).* :
String number = result.replaceAll(".*ssl_token=(\\d+).*", "$1");
Outputs
4366738602809990
You can do it with regex. It would probably be better to change the specifications of the input string so that each key/value pair is separated by an ampersand (&) so you could split it (similar to HTTP POST parameters).
Pattern p = Pattern.compile(".*ssl_token=([0-9]+).*");
Matcher m = p.matcher(result);
if(m.matches()) {
long token = Long.parseLong(m.group(1));
System.out.println(String.format("token: [%d]", token));
} else {
System.out.println("token not found");
}
Search index of ssl_token. Create substring from that index. Convert substring to number. To number can extract number when it is at the beggining of the string.

Converting string data from an array of data arranged in columns

I'm trying to convert a string array that is itself a part of another array fed into Java from an external file.
There are two parts to this question:
How do I convert the string's substring elements to doubles or ints?
How do I skip the header which is itself a part of the string?
I have the following piece of code that is NOT giving me an error but neither is it giving me output. The data is arranged in columns, so as far as the split, I'm not sure what delimiter to use as the argument for that method. I've tried \r, \n, ",", " " and nothing works.
str0 = year.split(",");
year = year.trim();
int[] yearData = new int[str0.length-1];
for(i = 0; i < str0.length-1; i++) {
yearData[i] = Integer.parseInt(str0[i]);
System.out.println(yearData[i]);
}
The code you have provided is not working. Anyway consider the given example which is using Regular Expression, where you found all the numbers in the string, so our regular expression works well. By changing the Regular Expression you can get the substring as well as you can skip the head part. I hope it would help.
String regEx = "[+|-]?(\\d+(\\.\\d*)?)|(\\.\\d+)";
String str = "256 is the square of 16 and -2.5 squared is 6.25 “ + “and -.243 is less than 0.1234.";
Pattern pattern = Pattern.compile(regEx);
Matcher m = pattern.matcher(str);
int i = 0;
String subStr = null;
while(m.find()) {
System.out.println(m.group());
Try something like this:
year = year.trim(); // This should come before the split()...
str0 = year.split("[\\s,;]+"); // split() uses RegEx...
int[] yearData = new int[str0.length-1];
for(i = 0; i < str0.length-1; i++) {
yearData[i] = Integer.parseInt(str0[i]);
System.out.println(yearData[i]);
}

Java sorting string based on two delimiters

I have a string of the following format
A34B56A12B56
And I am trying to sort the numbers into two arrays based on the prefixes.
For example:
Array A: 34,12
Array B: 56,56
What is the simplest way to go about this?
I have tried to use the String Tokenizer class and I am able to extract the numbers, however there is no way of telling what the prefix was. Essentially, I can only extract them into a single array.
Any help would be appreciated.
Thanks!
Andreas seems to have provided a good answer already, but I wanted to practice some regular expressions in Java, so I wrote the following solution that works for any typical alphabetical prefix: (Comments are in-line.)
String str = "A34B56A12B56";
// pattern that captures the prefix and the suffix groups
String regexStr = "([A-z]+)([0-9]+)";
// compile the regex pattern
Pattern regexPattern = Pattern.compile(regexStr);
// create the matcher
Matcher regexMatcher = regexPattern.matcher(str);
HashMap<String, ArrayList<Long>> prefixToNumsMap = new HashMap<>();
// retrieve all matches, add to prefix bucket
while (regexMatcher.find()) {
// get letter prefix (assuming can be more than one letter for generality)
String prefix = regexMatcher.group(1);
// get number
long suffix = Long.parseLong(regexMatcher.group(2));
// search for list in map
ArrayList<Long> nums = prefixToNumsMap.get(prefix);
// if prefix new, create new list with the number added, update the map
if (nums == null) {
nums = new ArrayList<Long>();
nums.add(suffix);
prefixToNumsMap.put(prefix, nums);
} else { // otherwise add the number to the existing list
nums.add(suffix);
}
System.out.println(prefixToNumsMap);
}
Output : {A=[34, 12], B=[56, 56]}

Splitting a String which has longitude and latitude points

I have a kmlLayer which has several placemarkers on it. I want to iterate through these placemarkers and retrieve their coordinates so as to find the distance from my location to those points and only set the markers in a certain distance visible.
I have the following code
for (KmlPlacemark placemark: layer.getPlacemarks()) {
String s = ("placemarks",placemark.getGeometry()..getGeometryObject().toString());
String s has the following format:
lat/lng: (55.94569390835889,-3.190410055779333)
I want to extract the two coordinated from it. How can I do this?
If we can guarantee that the String to parse is always defined in a canonical way, so that is defined as lat+long ALWAYS, then using regex will be the easiest way:
Example:
String latLong = "lat/lng: (55.94569390835889,-3.190410055779333)";
Pattern patte = Pattern.compile("-?[0-9]+(?:.[0-9]+)?");
Matcher matcher = patte.matcher(latLong);
while (matcher.find()) {
System.out.println(Double.parseDouble(matcher.group()));
}
So, if you don't want to use Regex, do it by hands. First remove anything before "(" and after ")"
s = s.substring(s.indexOf("(")+1,s.indexOf(")")); //this will get you "55...,-3.19..."
And then split it by ",".
String[] strngs = s.split(",");
double lat = Double.parseDouble(strings[0]);
double lon = Double.parseDouble(string[1]);

split a string with multiple alphabets and letters - android

Very new to android java and I have a simple question. I have string for example like this :
P:38,AS:31,DT:231,AR:21
I want to split this into 4 different lists in the form :
P(list) = 38
AS(list) = 31
DT(list) = 231
AR(list) = 21
I tried split but it didnt get the job done ...
As long as the keys are always letters and the values are always integers, you can use regular expressions to parse these strings:
Hashtable<String, int[]> result = new Hashtable<String, int[]>();
Pattern pattern = Pattern.compile("([A-Z]+):(\\d+(?:,\\d+)*)");
Matcher matcher = pattern.matcher(input);
while (matcher.find()) {
String key = matcher.group(1);
String[] fields = matcher.group(2).split(",");
int[] values = new int[fields.length];
for (int i=0; i<values.length; i++)
values[i] = Integer.parseInt(fields[i]);
result.put(key, values);
}
Edit
"([A-Z]+):(\\d+(?:,\\d+)*)" is a regular expression that matches at least one uppercase letter ([A-Z]+) followed by a colon (:) followed by one more numbers separated by commas (\\d+(?:,\\d+)*). A single number is composed of one more digits (\\d+). The additional parentheses allow us to later access the individual parts of the input string using the group(int) method calls.
The java.util.regex.Matcher class allows us to iterate through the individual parts of the input string that match our regular expression. The find() method returns true as long as there is another substring in our input string that matches the regular expression. So with the input string "P:38,45,AS:31,DT:231,345,678,AR:21" the while loop would execute four times and the matcher variable would point to the following four substrings of the input string:
P:38,45
AS:31
DT:231,345,678
AR:21
We can then use the matcher's group(int) method to access the individual parts of each substring. matcher.group(1) accesses the text that was captured by the first parentheses of our regular expression (([A-Z]+)) which corresponds to "P", "AS", "DT", and "AR" in the individual loop iterations. Analogously, matcher.group(2) corresponds to the second parentheses of the regular expression ((\\d+(?:,\\d+)*)) which would return "38,45", "31", "231,345,678", and "21". So in the first iteration of the while loop key would hold "P" and fields would hold an array of strings ["38", "45"]. We can then parse the fields into actual integer values using Integer.parseInt(String) and store the key and the values in a Hashtable so that we can later retrieve the values for the individual keys. For example, result.get("DT") would return an array of integers with the values [231, 345, 678].
As #pobybolek said, you can use his method which he wrote to take the string and convert it into a hashtable, which uses the key and then the int values after it. The int values are stored in an array and the key is a string.
String input = master_string;
Hashtable<String, int[]> result = new Hashtable<String, int[]>();
Pattern pattern = Pattern.compile("([A-Z]+):(\\d+(?:,\\d+)*)");
Matcher matcher = pattern.matcher(input);
while (matcher.find())
{
String key = matcher.group(1);
String[] fields = matcher.group(2).split(",");
int[] values = new int[fields.length];
for (int pqr=0; pqr<values.length; pqr++)
{
values[pqr] = Integer.parseInt(fields[pqr]);
// values[pqr] = fields[pqr];
}
result.put(key, values);
}
the above code splits the given string into its keys and the values after the key into an integer array, this can also be changed into a String key, String[] array as seen in the second line of my code.

Categories

Resources