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


so, i'm receiving array of string , split each element , save new array , have faced lot of problems , came 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; (int = 0; < 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 can see have create if-statement save 2 elements, know it's bad approach that's able come :(

you can calculate index in result array index in input array:

string[] t = new string[2*timeslots.length];  (int = 0; < 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 trims both strings)


Comments

Popular posts from this blog

PySide and Qt Properties: Connecting signals from Python to QML -

c# - DevExpress.Wpf.Grid.InfiniteGridSizeException was unhandled -

scala - 'wrong top statement declaration' when using slick in IntelliJ -