-2
Ex String Param=Value1:100,Value2:2000,Value3:30000:

What is the best way in java to trim the above mentioned string format to get the First element's value?

Result should be 100 (from the above mentioned Ex string param).

Henk van Boeijen
  • 7,357
  • 6
  • 32
  • 42
svik
  • 1
  • 3
  • Read up about splitting and slicing strings in Java. – Akshay Damle Jan 06 '16 at 07:05
  • 2
    Please state what your criteria for "best" are. Fastest, least code, simplest, most "elegant"? The answer is most likely different in each case ... and most likely a matter of opinion in nearly all cases. – Stephen C Jan 06 '16 at 07:30

2 Answers2

1

Assuming you have a String e = "Value1:100,Value2:2000,Value3:30000";

Your next step would be to analyze its structure. In this case it is very simple key:value which is comma separated.

We have to split at every "," and then ":".

String[] keyValues = e.split(",");

for(String keyValue : keyValues) {
  String tupel = keyValue.split(":");
  // tupel[0] is your key and tupel [1] is your value
}

You can now work with this. You can add these to a map to access it by name.

Also this How to search a string of key/value pairs in Java could be worth looking at.

Community
  • 1
  • 1
Marcinek
  • 2,144
  • 1
  • 19
  • 25
  • But this is not the best way to do I think so. If you have a 100s of values then this loop will repeat that many times. – SatyaTNV Jan 06 '16 at 07:19
  • 1
    @Satya - On the other hand, if the OP doesn't need to do it hundreds of times, then it is just fine. The problem is that "best" is subjective ... unless the OP specifies the criteria for deciding (which he doesn't). – Stephen C Jan 06 '16 at 07:28
  • @StephenC I think this is the best, it is clean, fast and does the job right. – Koray Tugay Jan 06 '16 at 07:44
  • You have specified two potentially contradictory criteria - "clean" and "fast". This makes your question inherently Opinion-based. – Stephen C Jan 06 '16 at 07:55
0

If you only want the first value, you can take a substring up to the first ',':

String p = "Value1:100,Value2:2000,Value3:30000:";
int firstComma = p.indexOf(',');
if(firstComma >= 0) {
    p = p.substring(0, firstComma);
}
String tuple[] = p.split(":");
Rolf Rander
  • 3,221
  • 20
  • 21