Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting up a string in Java

Can anyone advise on an issue that's been bugging me? I have a Java .jar file which returns a string from a method made up as follows:

integer integer integer block_of_text

That is three integers which may be positive or negative, each separated by single spaces, and then another space before a block of text which may consist of any characters but which should not contain carriage returns. Now I suppose I can read a substring up to the space character for each of the initial integers and then simply read the remaining text in one go.

I should add that the block of text is not to be broken down regardless of what it contains.

But can anyone suggest a better alternative?

Thanks to the respondents. This has saved me a headache!

like image 766
Mr Morgan Avatar asked Mar 03 '12 19:03

Mr Morgan


3 Answers

You can use the form of String#split(regex,limit) which takes a limit:

String s = "123 456 789 The rest of the string";
String ss[] = s.split(" ", 4);
// ss = {"123", "456", "789", "The rest of the string"};
like image 91
maerics Avatar answered Nov 09 '22 05:11

maerics


You can use String.split with space as a separator, and set a limit of 4:

String[] result = s.split(" ", 4);

You could also use a Scanner. This will not only split the text, but also parse the integers to int. Depending on whether you need the three integers as int or String, you might find this more convenient:

Scanner scanner = new Scanner(s);
int value1 = scanner.nextInt();
int value2 = scanner.nextInt();
int value3 = scanner.nextInt();
scanner.skip(" ");
String text = scanner.nextLine();

See it working online: ideone.

like image 7
Mark Byers Avatar answered Nov 09 '22 06:11

Mark Byers


One simple way (since you said there won't be newlines in block_of_text) is to use a Scanner. It is a tool to break up input based upon a certain delimited, and return appropriate types back to you. For example, you can use the methods hasNextInt() and nextInt() to check for an integer in the input, and to actually pull it from the stream.

For example:

Scanner scanner = new Scanner(System.in); // Arg could be a String, another InputStream, etc
int[] values = new int[3];
values[0] = scanner.nextInt();
values[1] = scanner.nextInt();
...
String description = scanner.nextLine();

You could use this until you've exhausted the input stream, and begin using the values as you need.

Here are more details on how to use Scanner: If ... is not an int {

like image 3
pseudoramble Avatar answered Nov 09 '22 06:11

pseudoramble