How to get number from string array in java - java

i have a string like String[] str = {"[5, 2, 3]","[2, 2, 3, 10, 6]"} and i need to take numbers to add into an integer list.
i tried to split first index into numbers to see if it will work, looks like:
String[] par = str[0].split("[, ?.#]+");
After the split i tried to see what array i get:
for(String a: par)
System.out.println(a);
But when i wrote that code i get an array like this:
[5
2
3]
So, how can i get rid of this square brackets?

Instead of your current pattern, I would use \\D+ which will split on one or more non-digits. Add a guard for the empty string too. Something like
String[] str = { "[5, 2, 3]", "[2, 2, 3, 10, 6]" };
for (String par : str) {
for (String t : par.split("\\D+")) {
if (t.isEmpty()) {
continue;
}
System.out.println(Integer.parseInt(t));
}
}
Outputs
5
2
3
2
2
3
10
6

Related

Java: How do you accept an integer array without using a for loop?

Is it possible to accept an integer array from user without using a for loop?
input will be :
4 //size
1 2 3 4 //array values
String stdin="1 2 3 4";
String str[]= stdin.split(" ");
int st[] = Integer.parseInt(stdin.split(" "));
this code does not work though
You can do this without a loop in Java 8 using stream.
Here is what you're looking for:
String str = "1 2 3 4";
int[] arr = Arrays.stream(str.split("\\s+"))
.map(String::trim).mapToInt(Integer::parseInt).toArray();
Goodluck, thanks.

How to format a string with a variable number of arguments

Lets say I have a method which returns a list with a random number of random numbers - we will call that method List<Integer> getRandomNumberOfRandomNumbers();
System.out.println(String.format("Here are the random numbers: %s", getRandomNumberOfRandomNumbers()));
I know this won't work but how can I achieve this effect?
Example Output
Here are the random numbers:
1 4 2 4
Here are the random numbers:
2 43 323 434 3423 54
It's easiest to just make getRandomNumberOfRandomNumbers return all of the numbers in a single String. Or you could do it all inline, like this:
getRandomNumberOfRandomNumbers().stream()
.map(Object::toString)
.collect(Collectors.joining(" "));
For example, if we have a List of Integers as below:
List<Integer> var = new ArrayList<>();
var.add(1);
var.add(4);
var.add(2);
var.add(4);
Then to print the List in your desired way, you can follow this:
System.out.println(String.format("Here are the random numbers:%n%n%s",
var.toString().replaceAll("[,\\[,\\]]", "")));
This outputs:
Here are the random numbers:
1 4 2 4
Here var is the list your function getRandomNumberOfRandomNumbers() is returning and we are converting it to String using var.toString() but it returns [1, 4, 2, 4]. So, we need to remove [, ] and ,. I used regular expression to replace them with an empty character. This is actually simple and easy way but not sure whether it is an efficient way!! Whenever i need to convert a Colletion to String, i use toString() method and then do some trick with regular expression to get my desired form of representation.
Update: After surfing web, i found few alternatives. (Preferred over my previous answer using List.toString())
StringJoiner : a relevant answer in SO
For example, in your case, you can do:
StringJoiner sj = new StringJoiner(" ");
for (Integer i : var) {
sj.add(String.valueOf(i));
}
System.out.println(sj.toString());
You can do the same with the following two alternatives.
StringUtils : a relevant answer in SO
String.Join : requires CharSequence
Another solution is iterating through the list and adding the values to a string builder before printing it out
like so:
StringBuilder stringBuilder = new StringBuilder();
for(Integer number : getRandomNumberOfRandomNumbers())
stringBuilder.append(number + " ");
System.out.println("Here are the random numbers: " + stringBuilder.toString().trim());

How do I convert a String to an String Array? [duplicate]

This question already has answers here:
How do I convert a String to an int in Java?
(47 answers)
Closed 7 years ago.
I'm reading from a file using Scanner, and the text contains the following.
[8, 3, 8, 2, 3, 4, 4, 4, 5, 8]
This was originally an integer Array that I had to convert to a String to be able to write in the file. Now, I need to be able to read the file back into java, but I need to be able to add the individual numbers together, so I need to get this String back into an array. Any help? Here's what I have:
File f = new File("testfile.txt");
try{
FileWriter fw = new FileWriter(f);
fw.write(Arrays.toString(array1));
fw.close();
} catch(Exception ex){
//Exception Ignored
}
Scanner file = new Scanner(f);
System.out.println(file.nextLine());
This prints out the list of numbers, but in a string. I need to access the integers in an array in order to add them up. This is my first time posting, let me know if I messed anything up.
You can use String#substring to remove the square brackets, String#split to split the String into an array, String#trim to remove the whitespace, and Integer#parseInt to convert the Strings into int values.
In Java 8 you can use the Stream API for this:
int[] values = Arrays.stream(string.substring(1, string.length() - 1)
.split(","))
.mapToInt(string -> Integer.parseInt(string.trim()))
.toArray();
For summing it, you can use the IntStream#sum method instead of converting it to an array at the end.
You don't need to read the String back in an Array, just use Regex
public static void main(String[] args) throws Exception {
String data = "[8, 3, 8, 2, 3, 4, 41, 4, 5, 8]";
// The "\\d+" gets the digits out of the String
Matcher matcher = Pattern.compile("\\d+").matcher(data);
int sum = 0;
while(matcher.find()) {
sum += Integer.parseInt(matcher.group());
}
System.out.println(sum);
}
Results:
86
List<Integer> ints = new ArrayList<>();
String original = "[8, 3, 8, 2, 3, 4, 4, 4, 5, 8]";
String[] splitted = original.replaceAll("[\\[\\] ]", "").split(",");
for(String s : splitted) {
ints.add(Integer.valueOf(s));
}

How to extract polynomial coefficients in Java?

Taking the string -2x^2+3x^1+6 as an example, how how to extract -2, 3 and 6 from this equation stored in the string?
Not giving the exact answer but some hints:
Use replace meyhod:
replace all - with +-.
Use split method:
// after replace effect
String str = "+-2x^2+3x^1+6"
String[] arr = str.split("+");
// arr will contain: {-2x^2, 3x^1, 6}
Now, each index value can be splitted individually:
String str2 = arr[0];
// str2 = -2x^2;
// split with x and get vale at index 0
String polynomial= "-2x^2+3x^1+6";
String[] parts = polynomial.split("x\\^\\d+\\+?");
for (String part : parts) {
System.out.println(part);
}
This should work. Sample output
polynomial= "-2x^2+3x^1+6"
Output:
-2
3
6
polynomial = "-30x^6+20x^3+3"
Output:
-30
20
3

Print array without brackets and commas

I'm porting a Hangman game to Android and have met a few problems. The original Java program used the console, so now I have to somehow beautify the output so that it fits my Android layout.
How do I print an array without the brackets and commas? The array contains slashes and gets replaced one-by-one when the correct letter is guessed.
I am using the usual .toString() function of the ArrayList class and my output is formatted like: [ a, n, d, r, o, i, d ]. I want it to simply print out the array as a single String.
I fill the array using this bit of code:
List<String> publicArray = new ArrayList<>();
for (int i = 0; i < secretWordLength; i++) {
hiddenArray.add(secretWord.substring(i, i + 1));
publicArray.add("-");
}
And I print it like this:
TextView currentWordView = (TextView) findViewById(R.id.CurrentWord);
currentWordView.setText(publicArray.toString());
Replace the brackets and commas with empty space.
String formattedString = myArrayList.toString()
.replace(",", "") //remove the commas
.replace("[", "") //remove the right bracket
.replace("]", "") //remove the left bracket
.trim(); //remove trailing spaces from partially initialized arrays
Basically, don't use ArrayList.toString() - build the string up for yourself. For example:
StringBuilder builder = new StringBuilder();
for (String value : publicArray) {
builder.append(value);
}
String text = builder.toString();
(Personally I wouldn't call the variable publicArray when it's not actually an array, by the way.)
For Android, you can use the join method from android.text.TextUtils class like:
TextUtils.join("",array);
first
StringUtils.join(array, "");
second
Arrays.asList(arr).toString().substring(1).replaceFirst("]", "").replace(", ", "")
EDIT
probably the best one: Arrays.toString(arr)
With Java 8 or newer, you can use String.join, which provides the same functionality:
Returns a new String composed of copies of the CharSequence elements joined together with a copy of the specified delimiter
String[] array = new String[] { "a", "n", "d", "r", "o", "i", "d" };
String joined = String.join("", array); //returns "android"
With an array of a different type, one should convert it to a String array or to a char sequence Iterable:
int[] numbers = { 1, 2, 3, 4, 5, 6, 7 };
//both of the following return "1234567"
String joinedNumbers = String.join("",
Arrays.stream(numbers).mapToObj(String::valueOf).toArray(n -> new String[n]));
String joinedNumbers2 = String.join("",
Arrays.stream(numbers).mapToObj(String::valueOf).collect(Collectors.toList()));
The first argument to String.join is the delimiter, and can be changed accordingly.
If you use Java8 or above, you can use with stream() with native.
publicArray.stream()
.map(Object::toString)
.collect(Collectors.joining(" "));
References
Use Java 8 Language Features
JavaDoc StringJoiner
Joining Objects into a String with Java 8 Stream API
the most simple solution for removing the brackets is,
convert the arraylist into string with .toString() method.
use String.substring(1,strLen-1).(where strLen is the length of string after conversion from arraylist).
the result string is your string with removed brackets.
I have used
Arrays.toString(array_name).replace("[","").replace("]","").replace(", ","");
as I have seen it from some of the comments above, but also i added an additional space character after the comma (the part .replace(", ","")), because while I was printing out each value in a new line, there was still the space character shifting the words. It solved my problem.
I used join() function like:
i=new Array("Hi", "Hello", "Cheers", "Greetings");
i=i.join("");
Which Prints:
HiHelloCheersGreetings
See more: Javascript Join - Use Join to Make an Array into a String in Javascript
String[] students = {"John", "Kelly", "Leah"};
System.out.println(Arrays.toString(students).replace("[", "").replace("]", " "));
//output: John, Kelly, Leah
You can use the reduce method provided for streams for Java 8 and above.Note you would have to map to string first to allow for concatenation inside of reduce operator.
publicArray.stream().map(String::valueOf).reduce((a, b) -> a + " " + b).get();
I was experimenting with ArrayList and I also wanted to remove the Square brackets after printing the Output and I found out a Solution. I just made a loop to print Array list and used the list method " myList.get(index) " , it works like a charm.
Please refer to my Code & Output below:
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
ArrayList mylist = new ArrayList();
Scanner scan = new Scanner(System.in);
for(int i = 0; i < 5; i++) {
System.out.println("Enter Value " + i + " to add: ");
mylist.add(scan.nextLine());
}
System.out.println("=======================");
for(int j = 0; j < 5; j++) {
System.out.print(mylist.get(j));
}
}
}
OUTPUT
Enter Value 0 to add:
1
Enter Value 1 to add:
2
Enter Value 2 to add:
3
Enter Value 3 to add:
4
Enter Value 4 to add:
5
=======================
12345
Just initialize a String object with your array
String s=new String(array);

Categories