• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Split up string into pairs of numbers

 
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I have a text file that contains the following:

3,5,6,7,34,89,23.66,89.5,90.22,100.33,45.33,78.44

I would like to split it up into pairs of numbers. For the first pair, I would like the first number to be 3 and the second number to be 5. For the second pair, the first number should be 6 and the second number should be 7 and so on. How would I do this in Java?

 
Bartender
Posts: 1845
10
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Have you tried anything so far?

One way would be to read the whole line of text into a String and use the split() method to get a String[]
From there it should be trivial to split the numbers into pairs.



 
Marshal
Posts: 79178
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You can create a Scanner from that String and tell is to use the comma as a delimiter.
 
Alissa Horner
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Stefan Evans wrote:Have you tried anything so far?

One way would be to read the whole line of text into a String and use the split() method to get a String[]
From there it should be trivial to split the numbers into pairs.





I have the following:

String input = "12 45 44 6 74 75 8 56 44";
String[] pairs = input.split("(?<!\\G\\d+)\\s");


How would I change this so that it can handle numbers with a decimal point?

>
 
Stefan Evans
Bartender
Posts: 1845
10
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
What happened to the commas?
The string split method works by default with commas.

>How would I change this so that it can handle numbers with a decimal point?
I would put the commas back in, and remove the regular expression.
 
reply
    Bookmark Topic Watch Topic
  • New Topic