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

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

Related

Is there a better way to convert a character literal array into a character object array in Java? [duplicate]

This question already has answers here:
Converting String to "Character" array in Java
(14 answers)
Closed 5 months ago.
I am trying to convert a character literal array into a character object array.
Right now I am just using a for loop like:
char[] charLiterals = "abcdefghijklmnopqrstuvwxyz".toCharArray();
Character[] charObjects = new Character[charLiterals.length];
for (int character = 0; character < charLiterals.length; character++) {
charObjects[character] = Character.valueOf(charLiterals[character]);
}
But is there a more concise way to do this?
A simple one liner would do.
Character[] charObjects = "abcdefghijklmnopqrstuvwxyz".chars().mapToObj(c -> (char)c).toArray(Character[]::new);
According to this article there are multiple ways to do that. But I believe that all of them under the hood boil down to an iteration similar to the one you provided.
If you don't mind using external libraries, then org.apache.commons.commons-lang3:3.12.0 might be the shortest and cleanest approach:
int[] input = new int[] { 0, 1, 2, 3, 4 };
Integer[] expected = new Integer[] { 0, 1, 2, 3, 4 };
Integer[] output = ArrayUtils.toObject(input);
assertArrayEquals(expected, output);
Just leaving the part of converting String into Char array and directly assigning string's char value to Character array.
String str = "abcdefghijklmnopqrstuvwxyz";
Character[] charObjects = new Character[str.length()];
for(int i = 0; i < str.length(); i++) {
charObjects[i] = Character.valueOf(str.charAt(i));
}

How do I split a list with fixed size number into another list?

So I have a loop in regex,
List<String> data = new ArrayList<>();
List<String> inputData = // String array
Pattern pattern = Pattern.compile(regex);
inputData.forEach(i -> {
Matcher matcher = pattern.matcher(i);
while(matcher.find()) {
data.add(matcher.group().trim());
}
});
Now data will have an array of strings like this,
data = ['text', 'text2', 'text3', 'text4', 'text5', 'text6']
I want to divide this array of strings into a fixed size of 3.
data = [['text', 'text2', 'text3'], ['text4', 'text5', 'text6']]
If you want to split this list into sublist with fixed size - you can use Guava, or smth else
You can find related docs here - https://guava.dev/releases/31.0-jre/api/docs/com/google/common/collect/Lists.html#partition(java.util.List,int)
Example:
List<Integer> intList = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8);
List<List<Integer>> subSets = Lists.partition(intList, 3);

How to get number from string array in 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

Java BufferReader To array stored by lines

Given a list of polynoms I need to store them on different arrays depending on the row.
Example:
5 -4 2 0 -2 3 0 3 -17 int[] a = {-17, 3, 0, 3, -2, 0, 2, -4, 5}
4 -2 0 1 int[] b = {1, 0, -2, 4}
First line I need to put on the array a[], and the second one on array b[]
Tried something like this:
File file=new File("Pol.txt");
BufferedReader b=new BufferedReader(new InputStreamReader(new FileInputStream(file)));
Pattern delimiters=Pattern.compile(System.getProperty("line.separator")+"|\\s");
String line=b.readLine();
First, you will want to make sure that any file reading objects are always properly cleaned up. A try-with-resources block is your best bet, or otherwise a try finally block.
try(BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(
new FileInputStream(file))) {
//code using bufferedReader goes here.
}
You should not need to use the Pattern class here. It's a simple case of reading a line and using the String.split method. e.g.
String line = bufferedReader.readLine();
//if (line == null) throw an exception
String[] splitLine = line.split("\\s+");
Now the splitLine variable will contain an array of Strings, which is each of the elements from the original line, as separated by spaces. The split method takes a String which is the regular expression representing the 'delimiter' of your values. For more information on regular expressions in Java, try this. The "\\s+" represents any whitespace character or characters These can be 'parsed' to int values using the Integer.parseInt method, like this:
int[] a = new int[splitLine.length];
for(int i = 1; i <= splitLine.length; i++) {
int parsed = Integer.parseInt(splitLine[i]);
a[splitLine.length - i] = parsed;
}
The parseInt method may throw a NumberFormatException, for example if you give it the String "Hello world". You can either catch that or let it be thrown.

Input from text file to array

The input will be a text file with an arbitrary amount of integers from 0-9 with NO spaces. How do I populate an array with these integers so I can sort them later?
What I have so far is as follows:
BufferedReader numInput = null;
int[] theList;
try {
numInput = new BufferedReader(new FileReader(fileName));
} catch (FileNotFoundException e) {
System.out.println("File not found");
e.printStackTrace();
}
int i = 0;
while(numInput.ready()){
theList[i] = numInput.read();
i++;
Obviously theList isn't initialized, but I don't know what the length will be. Also I'm not too sure about how to do this in general. Thanks for any help I receive.
To clarify the input, it will look like:
1236654987432165498732165498756484654651321
I won't know the length, and I only want the single integer characters, not multiple. So 0-9, not 0-10 like I accidentally said earlier.
Going for Collection API i.e. ArrayList
ArrayList a=new Arraylist();
while(numInput.ready()){
a.add(numInput.read());
}
You could use a List<Integer> instead of a int[]. Using a List<Integer>, you can add items as desired, the List will grow along. If you are done, you can use the toArray(int[]) method to transform the List into an int[].
1 . Use guava to nicely read file's 1st line into 1 String
readFirstLine
2 . convert that String to char array - because all of your numbers are one digit lengh, so they are in fact chars
3 . convert chars to integers.
4 . add them to list.
public static void main(String[] args) {
String s = "1236654987432165498732165498756484654651321";
char[] charArray = s.toCharArray();
List<Integer> numbers = new ArrayList<Integer>(charArray.length);
for (char c : charArray) {
Integer integer = Integer.parseInt(String.valueOf(c));
numbers.add(integer);
}
System.out.println(numbers);
}
prints: [1, 2, 3, 6, 6, 5, 4, 9, 8, 7, 4, 3, 2, 1, 6, 5, 4, 9, 8, 7, 3, 2, 1, 6, 5, 4, 9, 8, 7, 5, 6, 4, 8, 4, 6, 5, 4, 6, 5, 1, 3, 2, 1]

Categories