Splitting a string into multiple Arrays - java

For my program, the input from the user will be something like this:
{1,2,3} {1,2} {4,5,6}
There can be multiple { } with any number of ... numbers inside.
I already made a 2 dimensional array with an array for each sequence of numbers: {}
I am having troubling splitting them into their respective arrays so it will be something like this:
Array[0] = ["1","2","3"]
Array[1] = ["1","2"]
Array[2] = ["4","5","6"]
How would i split it like that? i dont know if i can split this string into n number of strings since the number of sequences depends on user.

Split the string on " " (space), and from there remove the curly brackets (perhaps take a substring, from index 1 to index length-1). Then split on comma. That should return a string array containing numbers. From there parse the strings to integers, and store in an integer array.

This code will help you
public class T {
public static void main(String[] args) {
String s = "{1,2,3} {1,2} {4,5,6}";
String[] mainArray = s.split(" ");
String[][] result = new String[mainArray.length][];
int count = 0;
for (String t : mainArray) {
result[count] = t.split(",");
count++;
}
}
}

var x = "{1,2,3} {1,2} {4,5,6}";
var y = x.split(" ");
var k =[];
for(var i = 0; i < y.length; i++){
k.push((y[i].substring(1,y[i].length-1)).split(","));
}
Well, this be how you would do it in javascript, algorithm.(my bad mis-read the tag)
K will be the final array.

Create a collection of arrays (of the type the input arrays will be, if known).
Split the array on "{".
With the resulting array, you remove the "}" from each string and split it on ",".
Then iterate over the resulting string array, parsing its contents and building an array of your entry type.
Finally, add that array to your collection.
This assumes there are no sub-arrays, true for your sample input. It does not assume the user added spaces between the given arrays, however; that is something I wouldn't trust a user to remember.

Related

How to split a string into several strings of equal sizes

I have to convert a binary number to a hex number. The way I have decided to do this is to split the binary string into several strings of length 4 and assign each string its corresponding value in hex number (i.e. 1000 = 8, 1101 = D).
I have seen several question asking for a way to split a string into strings of size 4 the same thing but all of those solutions used a regex that gave a single string. For example I found this line of code in a solution:
System.out.println(Arrays.toString("String".split("(?<=\G.{4})")));
When I tried to use it with the binary number "10011000", I got "[1001, 1000]" but as a single string (the brackets, comma, and blank space were included as characters) and I was left with the same problem, how do I split a string.
Is there a way to split a string into an array of smaller strings?
You can try making the string a char array and then into another array of strings, add each 4 characters of the char array.
Try this:
String BinaryNumber = "10011010";
char[] n = new char[BinaryNumber.length()];
for(int i=0; i<BinaryNumber.length(); i++){
n[i] = BinaryNumber.charAt(i);
}
String str;
String[] NumberArray = new String[(BinaryNumber.length())/4];
int count = 0;
for(int i=0; i<BinaryNumber.length(); i+=4){
str = String.valueOf(n[i])+String.valueOf(n[i+1])+String.valueOf(n[i+2])+String.valueOf(n[i+3]);
NumberArray[count] = str;
count++;
}
I think this might be the solution, though it will only work if the length of the BinaryNumber is divisible by 4.
Try it like this.
String binaryNumber = "110101111";
// first make certain the binary string is a multiple of length four so
// pad on the left with 0 bits.
binaryNumber = "0".repeat(3 - (binaryNumber.length()+3) % 4)
+ binaryNumber;
// Then you can just split it like this as you described.
String[] groups = binaryNumber.split("(?<=\\G.{4})");
for (String v : groups) {
System.out.println(v);
}
prints
0001
1010
1111

How to take an array of strings and get the ASCII value of each character in EACH string in Java?

So i have an array of strings. Each index contains a string like "abc" "fnsb" "feros". I want to pass in this array of strings through a for loop that can get each character's ASCII value of ALL the strings listed above and possibly store each string's character's ASCII value in another array. For example, if my array of strings has
mystrings[0] = hi
mystrings[1] = hello
mystrings[2] = farewell
I want it to take the ASCII values of "h" and "i" and store it in an newarray[0], then take the ASCII values of "h","e","l","l","o" and store it into newarray[1], and ETC.
Note: Above is a bunch of pseudocode. Here is what I actually have:
String[] mystrings= new String[100];
double [] newarray = new double[100];
for (int x=0; x<100; x++){
char character = mystrings[x].charAt(x);
int ascii = (int) character;
newarray[x] = ascii;
System.out.println(newarray[x]);
}
Another note: There are indeed multiple strings stored in each index of the mystrings array. It's just in another part of my code that I don't want to share. So please assume that the "mystrings" array is properly filled with various strings. Thank you!
The key issue in your pseudocode is that the result must be not simply an array, but an array of arrays:
int[][] newarray = new int[mystrings.length][];
The second issue is that getting character codes must be done in a separate loop, nested inside the first one. The loop must go from zero to mystring[i].length():
char character = mystrings[x].charAt(y);
// ^
Note that charAt parameter is not the same as x in mystrings[x], because it needs to be a separate loop.
String s = "hello";
byte[] bytes = s.getBytes("US-ASCII");
Here's a Java 8 solution:
String[] mystrings = {"hi", "bye"};
List<List<Integer>> result;
result = Arrays.stream(mystrings)
.map(s -> s.chars()
.mapToObj(e -> (char) e)
.collect(Collectors.toList()))
.map(chars -> chars.stream()
.map(Integer::new)
.collect(Collectors.toList())
)
.collect(Collectors.toList());
... and the output would be:
[[104, 105], [98, 121, 101]]

Split an array every time a letter appears to form a longer array in Java

I have split a string into an array every time a letter appeared, however I now want to split each string in the array into more arrays went another letter appears, adding an array below each split with the letter removed.
Here is my code:
private String input = "118u121u23n24"
private int y = 0;
private String[] split_main = new String[100];
private void split_u(){
String[] split = input.split("u");
for(int x=0; split.length>x; x++){
split_main[y] = split[x];
if(split.length>x+1)
split_main[y+1] = "+";
y +=2;
}
This splits my string into an array like this - creates a new array every time "u" appears and adds a plus
118
+
121
+
23n24
I now want to go through each of these arrays and look for the letter n and put it on a separate line so this will be the new array. However every time I have tried this I have got errors because I don't seem to be able to use the Split method again on the array. If using split is not possible then is there another way to do it?
118
+
121
+
23
n
24
Thanks in advance for any help.
Try this
String[] split = input.split("u|n");
u|n means that split string with by u or n, simply split string by two separator
while you want to add different separator in two levels you should write code like this.
String input = "118u121u23n24";
String[] s2;
ArrayList<String> main = new ArrayList<String>();
String[] split = input.split("u");
for(int x=0; split.length>x; x++){
s2 = split[x].split("n");
for(int k=0; k<s2.length; k++){
main.add(s2[k]);
if(s2.length>k+1)
main.add("n");
}
if(split.length>x+1)
main.add("+");
}
// print main array to test
for(int i=0;i<main.size();i++)
System.out.println(main.get(i));
I'd suggest that you simply split on all the letters at once, using a regex:
String[] split = input.split("(+|n)");
If you require the intermediate steps, then the only way to do it is to iterate through the first split, building an array of results of splitting on the second letter. If you want to do this for multiple split patterns (not just "+" and "n"), you will need a general purpose procedure. Here's sample code:
/**
* Replaces one element of a list of strings with the results of
* splitting that element with a given pattern. A copy of the pattern
* is inserted between the elements of the split.
* #param list The list of elements to be modified
* #param pattern The pattern on which to split
* #param pos The position of the element to split
* #return The number of additional elements inserted. This is the amount by
* which the list grew. If the element was not split, zero is returned.
*/
int splitElements(List<String> list, String pattern, int pos) {
String[] split = list.get(pos).split(pattern);
if (split.length > 1) {
list.set(pos++, split[0]);
for (int i = 1; i < split.length; ++i) {
list.add(pos++, pattern);
list.add(pos++, split[i]);
}
} // else nothing to do
return (split.length << 1) - 1;
}
Then you would call this with each character with which you want to split:
private String input = "118u121u23n24";
private ArrayList<String> split_main = new ArrayList<String>();
split_main.add(input);
splitElements(split_main, "+", 0);
for (int i = 0; i < len; ++i) {
i += splitElements(split_main, "n", i);
}
It's possible. Use List instead of array to make inserting new items easy.
If you want arrays only, do it in two passes: first, iterate over input and count how many more cells you need because of n, then create new array of proper size and copy input contents to it, splitting along the way.

Each word divided on character in array

I have a problem with reading a txt file in Java. I have a File.txt (there is something like this:
Lalala
Java
C++
I want to 'convert' it into an array (for example for tab[0][0] will be L, then tab[0][1] will be a, etc.).
How can I do this?
If you have a String, you can convert it into an array of single characters by calling String.toCharArray();
First, split the String up into individual words...
String myExample = "Lalala Java C++";
String[] lines = myExample.split(" ");
Then split the individual lines into characters...
String myFirstLine = lines[0];
char[] letters = myFirstLine.toCharArray();
If you need it in a 2D array, you could then do something like this (this is a full example)...
String myExample = "Lalala Java C++";
String[] lines = myExample.split(" ");
char[][] myArray = new char[lines.length][0];
for (int i=0;i<lines.length;i++){
myArray[i] = lines[i].toCharArray();
}
This will assign the letters of line 1 to myArray[0][0], myArray[0][1], etc, and the letters of line 2 to myArray[1][0], myArray[1][1], etc, as you requested.
If what you want is a bidimensional array, the problem is that the width of the array need to be the length of the bigger word. I think is not a good practice.
Maybe if you create a list of arrays, it can be better:
List<char[]> arrays = new ArrayList<char[]>();
String[] words = fullText.split(" "); //or split("\\s+") if the text contains many lines or many spaces between the words
for(String word: words){
char[] charsOfWord = word.toCharArray();
arrays.add(charsOfWord);
}
This way, to access the frist character in the first word:
System.out.println(arrays.get(0)[0]);

String Manipulation in java

I have one array of strings. I want to get each of string, divide it in to 3 parts (number-string-number), and put each part in another array. At last I want to have 3 arrays which two of them store numbers and one of them stores strings. The number of spaces between numbers and strings are not fixed.
the format of the strings in the first array is:
-2.2052 dalam -2.7300
-3.0511 dan akan -0.1116
It will be great if you help me with a sample code.
Here's the algorithm you could implement :
Create your 3 output arrays. They should all have the same length as the original string array
iterate through your original array.
for each string, find the index of the first space character and the index of the last space character. (look into the javadoc of the String class for methods doing that)
extract the substring before the first space, the substring between the first and last space, and the substring after the last space. The javadoc should help you.
Convert the first and third substring into an int (see the javadoc for Double for how to do it)
store the doubles and the string into the ouput arrays.
You can use indexOf and lastIndexOf to achieve this. Try following:
String arrayWithStringAndNumber[] = new String[2];
arrayWithStringAndNumber[0] = "-2.2052 dalam -2.7300";
arrayWithStringAndNumber[1] = "-3.0511 dan akan -0.1116";
String numArray1[] = new String[2];
String numArray2[] = new String[2];
String strArray[] = new String[2];
String temp;
for (int i = 0; i < arrayWithStringAndNumber.length; i++) {
temp = arrayWithStringAndNumber[i];
numArray1[i]=temp.substring(0,temp.indexOf(" "));
numArray2[i]=temp.substring(temp.lastIndexOf(" ")+1);
strArray[i]=temp.substring(temp.indexOf(" ")+1,temp.lastIndexOf(" "));
}
Make sure all arrays are of same length.
For num arrays use type whatever you want. I think you may need double and then you can easily parse the value to fit in it.
Hope this helps.
You can use indexOf(int ch) and lastIndexOf(int ch) of String object to find the first and last whitespace character and divide the string using these two indexes. You can also trim the middle string part if needed.
So:
String[] input; // given
Double[] firstNumbers = new Double[input.length];
String[] middleParts = new String[input.length];
Double[] secondNumbers = new Double[input.length];
for(int i = 0; i < input.length; i++) {
String line = input[i];
int firstWhitespace = line.indexOf(" ");
int lastWhitespace = line.lastIndexOf(" ");
String firstNumber = line.substring(0, firstWhitespace);
String middlePart = line.substring(firstWhitespace, lastWhitespace+1);
String secondNumber = line.substring(lastWhitespace+1, line.length());
// parse numbers to double, add to an array
firstNumbers[i] = Double.parseDouble(firstNumber);
middleParts[i] = middlePart;
secondNumbers[i] = Double.parseDouble(secondNumber);
}
Usually every programming language has functions for operating on strings data. Common set of functions is
length (or len) - to get length of string
find (or indexOf or somthing like this) - to find position of character of substring
substring (or substr) - to get substring of N characters from postion P
often
left/right - to get substring of N characters from left or right string's side
Trim/leftTrim/rightTrim - to trim from left and/or right string's side all space-characters or given as function parameter character.
Always as you need to operate on strings data, try to read documentation or google. You always will find information at Internet. Good luck!

Categories

Resources