简体   繁体   中英

Split a string in to words and numbers

I have a string as below.

sil(0.14,0.25) in(0.25,0.82) order(0.82,1.03) to(1.03,1.17) entertain(1.17,1.94) the(1.94,2.04) people(2.04,2.41) who(2.41,2.54) are(2.54,2.6) listening(2.6,3.13) to(3.13,3.29) you, ..........

I have split the string as follow.

 sil 0.14 0.25 in 0.25 0.82 order 0.82 1.03 to 1.03 1.17 

What I want is to find the difference between the two numbers after each word. eg : sil = 0.25 - 0.14 in = 0.82 - 0.25

Please let me know how to do this task.

Thaks a lot.

Here is my solution :

  1. .split() by " " so you can get array like {sil(0.14,0.25), in(0.25,0.82) ...}
  2. take each of this array and .parse() by splitting "," and subtract first by second

     private static float parse(String s) { String str = s.substring(s.indexOf('(')+1, s.length()-1); String[] numbers = str.split(","); return Float.parseFloat(numbers[1]) - Float.parseFloat(numbers[0]); } public static void main(String[] args) { String s = "sil(0.14,0.25) in(0.25,0.82) order(0.82,1.03) to(1.03,1.17) entertain(1.17,1.94) the(1.94,2.04) people(2.04,2.41) who(2.41,2.54) are(2.54,2.6) listening(2.6,3.13) to(3.13,3.29)"; String[] sArray = s.split(" "); for(String str : sArray){ String head = str.substring(0, str.indexOf('(')); System.out.println(head + "=" +parse(str)); } } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM