Java line split

Can anyone advise a problem that bothered me? I have a Java.jar file that returns a string from a method composed as follows:

integer integer integer block_of_text

These are three integers that can be positive or negative, each of which is separated by single spaces, and then another space in front of a block of text, which can consist of any characters, but should not contain a carriage return. Now I suppose I can read the substring before the space character for each of the starting integers, and then just read the remaining text at a time.

I must add that the block of text should not be broken, no matter what it contains.

But can anyone suggest a better alternative?

Thanks to the respondents. It saved me a headache!

+5
source share
4 answers

You can use a form String#split(regex,limit)that takes a restriction :

String s = "123 456 789 The rest of the string";
String ss[] = s.split(" ", 4);
// ss = {"123", "456", "789", "The rest of the string"};
+11
source

You can use String.splitwith space as a separator and set a limit of 4:

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

You can also use Scanner. This will not only split the text, but also analyze integers by int. Depending on whether you need three integers: intor String, you may 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 how it works on the Internet: ideone .

+7
source

( , block_of_text ) Scanner. . , hasNextInt() nextInt() .

:

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();

, .

, Scanner: ... int {

+3

- split.

String gen = "some texts here";
String spt[] = gen.split(" ");  //This will split the string gen around the spaces and stores them into the given string array


To remove the integers according to your question, run the array index with 3.
Hope this helps.

0
source

All Articles