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!
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"};
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.
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 {
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With