How to extract numbers from string in java - java

A program that I write recives an input like this
W 12.1 -1 2.2
B 1.2 3.2 1
And I need to check if the numbers are within coonstraints, so my idea is to store those numbers in array as integers. The numbers needs to be separated by the white spaces and the dots. Currently I have this code:
public static void main(String[] args) {
Scanner reader = new Scanner (System.in);
String input = reader.nextLine();
String[] numbers = input.substring(2,input.length()).split("\\.");
System.out.println(Arrays.toString(numbers));
}
For input W 12.1 -1 2.2 the output is [12, 1 -1 2, 2] As you see I managed to make it deal with the dots but I can't remove the white spaces. What is the most resource efficient way to achieve my task ?

The numbers needs to be separated by the white spaces and the dots.
Apply replaceAll("\\s", ".") to replace whitespaces by ..
String[] numbers = input.replaceAll("\\s", ".").substring(2,input.length()).split("\\.");
or use another regex in split() that accepts both . and whitespace char :
String[] numbers = input.substring(2,input.length()).split("\\.|\\s");

Related

I have one input having three different values. How can i scan three values form a single scanner

Next t lines contain three space-separated integers N, B1, B2 and
where N is the number of sides in the polygon and B1, B2 denote the
vertices that are colored black.
How can I extract numbers from single input using only one scanner object?
You can use String[] input = scanner.nextLine().split(" ") which will return a String array of the values that are entered on a single line. For example, if 1 2 3 is entered from the console, in input you will have ["1", "2", "3"].
Since you are using Scanner, a simple Scanner.nextInt() will suffice to read integers as long as they are separated by whitespace as mentioned in your problem statement.
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods.
For instance:
int n1,n2;
Scanner sc = new Scanner(System.in);
n1=sc.nextInt();
n2=sc.nextInt();
If the input is 20 40,
n1 will store 20 and n2 will store 40.
See:
https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html#nextInt--

Get int user input in java using delimiters and hasNext?

public static void main(String[] args) {
Scanner in = new Scanner(System.in);
in.useDelimiter(", "); // using delimiter ", "
int i = 1;
while(in.hasNextInt()){
i = in.nextInt();
System.out.println(i);
}
}
I am trying to get the input from console, but this code is
not printing last integer
How can I solve this problem. I don't want to use split and save the result in an array.
You will need to use a regex pattern.
in.useDelimiter(",?\\s");
OR, if it is not necessarily seperated by both spaces and commas (e.g. 1, 4,5465, 5):
in.useDelimiter("[,\\s]+"); // this is more permissive
With Scanner.useDelimiter, the string after your last input integer should match the delimiter pattern, for example with your pattern if you give "1, 3, 5, 6, " you will get 1 3 5 6 as output but if you give "1, 3, 5, 6" you will not get the last integer.

Extract number in a String java

I have a quite simple question here is that i have a string 0-1000
say str = "0-1000"
I successfully extract 0 and 1000 by using str.split("-")
Now, I am assigned to check the number because i am noticed that those two numbers can be a negative.
If I continue str.split("-"), then I will skip the negative sign as well.
Could anyone suggest methods for me?
Since String.split() uses regular expressions to split, you could do something like this:
String[] nos = "-1000--1".split("(?<=\\d)-";
This means you split at minus characters that follow a digit, i.e. must be an operator.
Note that the positive look-behind (?<=\d) needs to be used since you only want to match the minus character. String.split() removes all matching separators and thus something like \d- would remove digits as well.
To parse the numbers you'd then iterate over the array elements and call Integer.valueOf(element) or Integer.parseInt(element).
Note that this assumes the input string to be valid. Depending on what you want to achieve, you might first have to check the input for a match, e.g. by using -?\d--?\d to check whether the string is in format x-y where x and y can be positive or negative integers.
You can use regex like this :Works for all cases
public static void main(String[] args) {
String s = "-500--578";
String[] arr = s.split("(?<=\\d)-"); // split on "-" only if it is preceeded by a digit
for (String str : arr)
System.out.println(str);
}
O/P:
-500
-578

Using Split() in arithmetic formula

I thought a problem for a day but still cannot solve it.
I have a formula input like "11+1+1+2". without space
I want to split the formula according to the operator.
Then I wrote like these:
String s = "11+1+1+2";
String splitByOp[] = s.split("[+|-|*|/|%]");
for(int c=0; c < splitByOp.length; c++){
System.out.println(splitByOp[c]);
The output is:
11
1
1
2
I want to put the operand(the output) and also the operator(+) into an ArrayList. But how can I keep the operator after spliting them?
I try to have one more Array to split the number.
String operator[] = s.split("\\d");
But the result is 11 become 1 1. The length of operator[] is 5.
In other words, how can I perform like:
The output:
11
+
1
+
1
+
2
You need to split on a regex that is non consuming. Specifically, on "word boundary":
String[] terms = s.split("\\b");
A "word boundary" is the gap between the word char and a non-word char, but digits are classified as word chars. Importantly, the match is non-consuming, so all of the content of the input is preserved in the split terms.
Here's some test code:
String s = "11+1+1+2";
String[] terms = s.split("\\b");
for (String term : terms)
System.out.println(term);
Output:
11
+
1
+
1
+
2
public static void main(String[] args) {
String s = "11+1+1+2";
String[] terms = s.split("(?=[+])|(?<=[+])");
System.out.println(Arrays.toString(terms));
}
output
[11, +, 1, +, 1, +, 2]
You could combine lookahead/lookbehind assertions
String[] array = s.split("(?=[+])|(?<=[+])");

Get all the words in a sentence to an Arrya, ignoring whitespaces?

I want to read all the words in a sentence, to a Array. The problem is, there can be any number of white spaces between the words.
Example - "I am a good boy".
I have tried to use, Split method with white space as delimiter, but It will include the white space too as in the result.
The code I have used for this is below. Please ignore, the rest of the code.
class test {
public static void main(String[] args){
// c. Total the 100 elements of floating-point array c and print them.
double c[] = new double [100];
String str="BusNo 123 ArrivalTime 1030 Departure 1420 ";
String split[]=str.split(" ");
double total=0;
//Initialize C with Random Numbers from 0 to 10,000 Randomly
for(int k=0;k<100;k++){
c[k]=Math.random() *10000;
total+=c[k]; //Find the Total;
System.out.printf("C is %f\n",c[k]);
}
System.out.printf("Total is %f\n", total);
}
}
For my sample text as shown above, The split[] Array will be as follows
[I, , , , am, a, good, , , , , , boy]
I know, a workaround, that I can have a loop after my str.split( ) and ignore all the white spaces.
I would appreciate, if there is any better way to read directly without any spaces
You will need to split by whitespace, not just a single space, so that multiple spaces is considered one single delimiter.
String split[] = str.split("\\s+");
For spaces only, you can use
String[] strings = input.split("[ ]+");
or
String[] strings = input.split(" +");
For any whitespace (spaces, tabs, or new-lines), use
String[] strings = input.split("\\s+");

Categories

Resources