Java-Array Splitting - java

I have array of string {"All-Inclusive,All Inclusive","Luxury,Luxury","Spa-And-Relaxation,Spa & Relaxation"}
I want to split them based on "," with two arrays, first array {"All-Inclusive","Luxury","Spa-And-Relaxation"} and a second array {"All Inclusive","Luxury","Spa & Relaxation"}.
Can you kindly suggest how can it be done?

You could iterate your array of String(s). For each element, call String.split(String) and that will produce a temporary array. Make sure you got two String(s) from the array and then assign it to your output first and second like
public static void main(String[] args) {
String[] arr = { "All-Inclusive,All Inclusive", "Luxury,Luxury",
"Spa-And-Relaxation,Spa & Relaxation" };
String[] first = new String[arr.length];
String[] second = new String[arr.length];
for (int i = 0; i < arr.length; i++) {
String[] t = arr[i].split("\\s*,\\s*");
if (t.length == 2) {
first[i] = t[0];
second[i] = t[1];
}
}
System.out.printf("First = %s%n", Arrays.toString(first));
System.out.printf("Second = %s%n", Arrays.toString(second));
}
Output is
First = [All-Inclusive, Luxury, Spa-And-Relaxation]
Second = [All Inclusive, Luxury, Spa & Relaxation]

Related

Java splitting string using delimiter and store to different array

I was having some problem when trying to split string with delimiter and store to array. So basically I have a main array with input like this:
1564095_SINGLE_true, 1564096_SINGLE_true
What I am trying to do is split the string with delimiter and store to two different array. Below as how I loop thru the main array:
String arrayA = [];
String arrayB = [];
for(int i = 0; i < selectedRecord.length; i++) {
log.debug("HEY " + selectedRecord[i]);
String tempRecord = selectedRecord[i];
}
My desired output will be:
arrayA: 1564095_SINGLE, 1564096_SINGLE
arrayB: true, true
But I have no idea on how to split it. Any ideas? Thanks!
Here is one approach which splits in the input on the following regex pattern:
_(?!.*_)
This splits the input string on only the last underscore character. We can try iterating your collection of inputs, and then populating the two arrays.
List<String> inputs = Arrays.asList(new String[] {"1564095_SINGLE_true", "1564096_SINGLE_true"});
String[] arrayA = new String[2];
String[] arrayB = new String[2];
int index = 0;
for (String input : inputs) {
arrayA[index] = input.split("_(?!.*_)")[0];
arrayB[index] = input.split("_(?!.*_)")[1];
++index;
}
System.out.println("A[]: " + Arrays.toString(arrayA));
System.out.println("B[]: " + Arrays.toString(arrayB));
This prints:
A[]: [1564095_SINGLE, 1564096_SINGLE]
B[]: [true, true]
Does this help? Assuming you can apply basic checks (null, array length, etc)
String[] selectedRecord = {"1564095_SINGLE_true", "1564096_SINGLE_true"};
String[] arrayA = new String[selectedRecord.length];
String[] arrayB = new String[selectedRecord.length];
for (int i = 0; i < selectedRecord.length; i++) {
arrayA[i] = selectedRecord[i].substring(0, selectedRecord[i].lastIndexOf("_"));
arrayB[i] = selectedRecord[i].substring(selectedRecord[i].lastIndexOf("_")+1);
}
System.out.println(Arrays.asList(arrayA));
System.out.println(Arrays.asList(arrayB));
check below code
import java.util.*;
public class MyClass {
public static void main(String args[]) {
String str="1564095_SINGLE_true, 1564096_SINGLE_true";
System.out.println(str);
String arr[]=str.split(",");
ArrayList<String> arr1=new ArrayList();
ArrayList<String> arr2=new ArrayList();
for(int i=0;i<arr.length;i++)
{
String temp[]= arr[i].split("_");
for(int j=0;j<temp.length;j++)
{
if(j==2)
{
arr2.add(temp[j]);
}
else
{
arr1.add(temp[j]);
}
}
}
System.out.println(arr1);
System.out.println(arr2);
}
}
String selectedRecord[] = { "1564095_SINGLE_true", "1564096_SINGLE_true" };
String[] arrayA = new String[selectedRecord.length];
String[] arrayB = new String[selectedRecord.length];
for(int i = 0; i < selectedRecord.length; i++) {
String tempRecord = selectedRecord[i];
int size = tempRecord.split("_").length;
arrayB[i]= tempRecord.split("_")[size-1];
arrayA[i]= tempRecord.replace("_"+arrayB[i], "");
}
System.out.println("ArrayA: "+ Arrays.asList(arrayA));
System.out.println("ArrayB: "+ Arrays.asList(arrayB));
Output:
ArrayA: [1564095_SINGLE, 1564096_SINGLE]
ArrayB: [true, true]
Hi you can do something like this. Get the last index of the delimiter and substring the string.
String arrayA = [];
String arrayB = [];
for(int i = 0; i < selectedRecord.length; i++) {
int end = selectedRecord.lastIndexOf("_");
arrayA[i] = selectedRecord.substring(0, end);
arrayB[i] = selectedRecord.substring(end+1);
}
Of course here should be some datatype conversions. If you want to store "true"/"false" inside of the boolean array.

Convert a string into a multidimensional arrays with different lengths

I need to execute by command line a code that will provide a multidimensional array with elements with not necessarily equal lengths.
The execution string is bellow:
start /wait java -jar testMSMWithIndex.jar Foursquare_weather_day_root-type_type 0,1,2-4
I'm considering to pass the parameter 0,1,2-4 and then convert it in a multidimensional array with elements of different lengths in this case, i.e. {{0}, {1}, {2, 4}}.
Note that {{0, null}, {1, null}, {2, 4}} does not work to my problem.
Do you guys know how to develop a method or even get directly as an array from args?
I really appreciate any help you can provide.
It's doubtful that anything already exists to do this for you, so you'll have to parse the string for yourself. Something like this would do it:
public static int[][] parseRaggedArrayFromString(String s)
throws NumberFormatException {
String[] ss = s.split(",");
int[][] result = new int[ss.length][];
for (int i = 0; i < ss.length; ++i) {
if (!ss[i].contains("-")) {
result[i] = new int[1];
result[i][0] = Integer.parseInt(ss[i]);
} else {
String[] range = ss[i].split("-", 2);
int lo = Integer.parseInt(range[0]);
int hi = Integer.parseInt(range[1]);
int size = hi - lo + 1;
result[i] = new int[size > 0 ? size : 1];
int j = 0;
do {
result[i][j] = lo;
++lo;
++j;
} while (lo <= hi);
}
}
return result;
}
It's basically a split on , and -. From there is just handling the data. Comments in the code.
/**
* #author sedj601
*/
public class Main {
public static void main(String[] args) {
String input = "0,1,2-3";
String[] firstArray = input.split(",");//Split on ,.
String[][] outputArray = new String[firstArray.length][];//The array that will be holding the output
//Used to process the firstArray
for (int i = 0; i < firstArray.length; i++) {
if (firstArray[i].length() > 1) {//If the lenght is greater than one. split on -.
String[] secondArray = firstArray[i].split("-");
//Subtract the two numbers and add one to get the lenght of the array that will hold these values
int arrayLength = Integer.parseInt(secondArray[1]) - Integer.parseInt(secondArray[0]) + 1;
String[] tempArray = new String[arrayLength];
int increment = 0;//Keeps up with the tempArray index.
//loop from the first number to the last number inclusively.
for (int t = Integer.parseInt(secondArray[0]); t <= Integer.parseInt(secondArray[1]); t++) {
tempArray[increment++] = Integer.toString(t);//Add the data to the array.
}
outputArray[i] = tempArray;//Add the array to the output array.
} else {//If the lenght is 1, creat an array and add the current data.
String[] tempArray = new String[1];
tempArray[0] = firstArray[i];
outputArray[i] = tempArray;
}
}
//Print the output.
for (String[] x : outputArray) {
for (String y : x) {
System.out.print(y + " ");
}
System.out.println();
}
}
}
Output:
--- exec-maven-plugin:1.5.0:exec (default-cli) # JavaTestingGround ---
0
1
2 3
------------------------------------------------------------------------
BUILD SUCCESS
------------------------------------------------------------------------
Total time: 1.194 s
Finished at: 2021-01-08T00:08:15-06:00
------------------------------------------------------------------------
I really think that's possible when you create an array of type Object .(not a good idea) Since multi-D arrays can only hold arrays of same length (int[][]). Then you create and retrieve values from array by casting...
I am trying here to be creative and adopt to your requirements..
public class x {
public static void main(String[] args) {
Object[] arguments = new Object[args.length];
// Then make a loop to capture arguments in array..
// or add manually
arguments[0] = new String[]{args[0]};
arguments[1] = new String[]{args[1],args[2]};
//Then retrieve info from object later by casting
System.out.println(java.util.Arrays.toString((String[]) arguments[1]));
}
}
...
Although, please consider using a collection...
While I waited for the answer, I found a way to solve the problem.
The relevant information here is that we do not need to set the second array dimension in its instantiation.
The code is below:
// INPUT string = "2-3,1,4-5"
private static String[][] featuresConversion(String string) {
String[] firstLevel = string.split(","); // 1st lvl separator
String[][] features = new String[firstLevel.length][]; // Sets 1st lvl length only
int i = 0;
for (String element : firstLevel) {
features[i++] = element.split("-");
}
return features;
}
I want to thank you all. All suggested solutions also work fine!

How do I split a string into even parts then populate an array with those new strings?

I am working on a program and I will be asking the user to input a string full of characters with no spaces. I will then be splitting this string up into parts of three characters each, and I would like to populate an array with these new strings of three characters. So basically what I am asking is how would I create a method that takes an input string, splits it up into separate parts of three, then populates an array with it.
while (i <= DNAstrand.length()-3) {
DNAstrand.substring(i,i+=3));
}
This code will split the string up into parts of three, but how do I assign those values to an array in a method?
Any help is appreciated thanks!
Loop through and add all the inputs to an array.
String in = "Some input";
//in.length()/3 is automatically floored
String[] out = new String[in.length()/3];
int i=0;
while (i<in.length()-3) {
out[i/3] = in.substring(i, i+=3);
}
This will ignore the end of the String if it's length isn't a multiple of 3. The end can be found with:
String remainder = in.substring(i, in.length());
Finally, if you want the remainder to be part of the array:
String in = "Some input";
//This is the same as ceiling in.length()/3
String[] out = new String[(in.length()-1)/3 + 1];
int i=0;
while (i<in.length()-3) {
out[i/3] = in.substring(i, i+=3);
}
out[out.length-1] = in.substring(i, in.length());
Try this:
private static ArrayList<String> splitText(String text)
{
ArrayList<String> arr = new ArrayList<String>();
String temp = "";
int count = 0;
for(int i = 0; i < text.length(); i++)
{
if(count < 3)
{
temp += String.valueOf(text.charAt(i));
count++;
if(count == 3)
{
arr.add(temp);
temp = "";
count = 0;
}
}
}
if(temp.length() < 3)arr.add(temp);//in case the string is not evenly divided by 3
return arr;
}
You can call this method like this:
ArrayList<Strings> arrList = splitText(and the string you want to split);

String.Split() for a array of string and saving into a new array

So, I'm receiving an array of String and I would like to split each element and save it into a new array and I have faced a lot of problems with that and came up with a really bad solution:
String[] timeSlots = { "13:00:00 - 14:00:00", "15:00:00 - 16:00:00","17:00:00 - 18:00:00" };
String[] t = new String[6];
String temp[] = new String[6];
int j = 1;
for (int i = 0; i < 3; i++) {
temp = timeSlots[i].split("\\-");
if(j == 1){
t[0] = temp[0];
t[1] = temp[1].trim();
}
else if(j == 2){
t[2] = temp[0];
t[3] = temp[1].trim();
}
else{
t[4] = temp[0];
t[5] = temp[1].trim();
}
j++;
}
As you can see I have to create an if-statement to save two elements, I know that it's a bad approach but that's all I was able to come with :(
You can calculate the index in the result array from the index in the input array:
String[] t = new String[2*timeSlots.length];
for (int i = 0; i < timeSlots.length; i++) {
String[] temp = timeSlots[i].split("\\-");
t[2*i] = temp[0].trim();
t[2*i+1] = temp[1].trim();
}
Or use streams:
t = Arrays.stream(timeSlots).flatMap(slot -> Arrays.stream(slot.split("\\-")).map(String::trim)).toArray(String[]::new);
(this however trims both strings)
#Test
public void splitTimeSlotsToArray() {
String[] timeSlots = { "13:00:00 - 14:00:00", "15:00:00 - 16:00:00","17:00:00 - 18:00:00" };
// We already know how many times there are, each range (or slot)
// has two times specified in it. So it's the length of timeSlots times 2.
String[] times = new String[timeSlots.length*2];
for (int i = 0; i < timeSlots.length; i++) {
String timeSlotParts[] = timeSlots[i].split(" - ");
times[i*2] = timeSlotParts[0];
times[i*2 + 1] = timeSlotParts[1];
}
assertEquals(Arrays.asList(
"13:00:00", "14:00:00", "15:00:00", "16:00:00", "17:00:00", "18:00:00"
), Arrays.asList(times));
}
// This is a more preferable option in terms of readability and
// idiomatics in Java, however it also uses Java collections which you
// may not be using in your class
#Test
public void splitTimeSlotsToList() {
String[] timeSlots = { "13:00:00 - 14:00:00", "15:00:00 - 16:00:00","17:00:00 - 18:00:00" };
Collection<String> times = new ArrayList<>();
// Go over each time slot
for (String timeSlot : timeSlots) {
// Go over each time in each time slot
for (String time : timeSlot.split(" - ")) {
// Add that time to the times collection
times.add(time);
}
}
// you can convert the Collection to an array too:
// String[] timesArray = times.toArray(new String[timeStamps.size()]);
assertEquals(Arrays.asList(
"13:00:00", "14:00:00", "15:00:00", "16:00:00", "17:00:00", "18:00:00"
), times);
}
If the structure of your array is always the same you can first join the elements of your array to a string and split again after each hour. Example:
public static void main(String a[]){
String[] timeSlots = { "13:00:00 - 14:00:00", "15:00:00 - 16:00:00","17:00:00 - 18:00:00" };
String joined = String.join(" - ", timeSlots);// gives you a string like this "13:00:00 - 14:00:00 - 15:00:00 - 16:00:00 - 17:00:00 - 18:00:00"
String [] newArray = joined.split(" - ");
System.out.println(Arrays.toString(newArray));
}

Is there a way of traversing from string to int array and vice versa

In Java, given the array
int a[] = {1,2,3}
I can do Arrays.toString(a) to get
"[1,2,3]"
Is there an equally convenient way to return this String back to its antecedent array?
Or must I go through the whole split, for-loop, parseInt stuff?
UPDATE
Thanks everyone for all the thoughts. I rolled out my own function as
String src[] = data.split("\\D+");//data is intArrayAsString: [1,2,3]
int[] nums = new int[src.length - 1];
int ndx = 0;
for (String s : src) {
try {
nums[ndx] = Integer.parseInt(s);
ndx++;
} catch (NumberFormatException e) {
}
}
return nums;
Note: the word traverse seems to have thrown a few people off. By "traversing" I meant the ability to move back and forth from the string to the int array.
As far as i know, no.
But it's easy to do using Split.
I just did this, if you don't understand how to do it:
int[] arr = {1, 2, 3, 4};
String toString = Arrays.toString(arr);
System.out.println(toString);
// we know it starts with [ and ] so we skip it
String[] items = toString.substring(1, toString.length() - 1).split(",");
int[] arr2 = new int[items.length];
for (int i = 0; i < items.length; ++i)
{
arr2[i] = Integer.parseInt(items[i].trim()); // .trim() because it adds the space and parseInt don't like spaces
}
System.out.println(Arrays.toString(arr2));
(free to improve it, it's just a draft)
I don't know of any existing method, so I wrote you my own version:
import java.util.Arrays;
public class ArrayToString {
public static void main(String[] args) {
int a[] = {1,2,3};
String serialized = Arrays.toString(a);
System.out.println(serialized);
int[] b = stringToIntArray(serialized);
System.out.println(Arrays.toString(b));
}
private static int[] stringToIntArray(String serialized) {
// remove '[' and ']'
String raw = serialized.replaceAll("^\\[(.*)\\]$", "$1");
// split by separators
String[] splitStrings = raw.split(", ");
// create new int array
int[] b = new int[splitStrings.length];
for (int i = 0; i < splitStrings.length; i++) {
String splitString = splitStrings[i];
// parse each text individually
b[i] = Integer.parseInt(splitString);
}
return b;
}
}

Categories

Resources