Concatenating String Arrays in For Loops with String conditions - java

I currently am running a for loop which reads a List object and then splits them into arrays. Here is the sample code:
List<String> lines = Arrays.asList("foo,foo,foo","bar,baz,foo","foo,baz,foo", "baz,baz,baz", "zab,baz,zab");
for (String line : lines){
String[] array = line.split(",");
String[] arraySplit2 = array[0].split(",");
System.out.print(Arrays.toString(arraySplit2));
}
The output is:
[foo][bar][foo][baz][zab]
I wish to concatenate the array strings into a single one under the loop so that it displays:
[foo, bar, foo, baz, zab]
I'm having a bit of trouble because the conditions of the loop prevent me from doing the increase int i trick and using System.arraycopy(). I'm open to ideas such as changing the structure of the loop itself.

You seem to be trying to create an array out of first items from each line.
First, So you need to create the result array first with the size of number of lines:
String[] result = new String[lines.size()];
int index = 0;
You do not need the second split, in the for loop populate the result array:
result[index++] = array[0]
After the loop print your result array.

Not 100% sure on what you want, but I guess something like this:
List<String> outList = new ArrayList<String>();
for (String line : lines) {
String[] array = line.split(",");
outList.add(array[0]);
}
String[] outStr = outList.toArray(new String[0]);
System.out.println(Arrays.toString(outStr));

Related

Splitting a String array and storing in a list

There is a string[] arr = {"aa-bb-cc","dd-bb-ee","aa-hh-gg"} which needs to be split on the basis of , and -. The values aa,dd,aa should be stored in one list whereas bb,hh in another list. I have written this code snippet:
String[] arr = {"aa-bb-cc","dd-bb-ee","aa-hh-gg"};
for(int i=0;i<arr.length;i++){
newArr = arr[i].split(",");
for(int j=0;j<newArr.length;j++){
resultArr = newArr[j].split("-");
appList.add(resultArr[0]);
prodList.add(resultArr[1]);
rolList.add(rresultArr[2]ol);
}
Above approach could be better if we do arr[i].split in another way so that we can run only one loop but I could not achieve that so far.
I wanted to know is there any best way to achieve the requirement.
You don't need to split it using , ,since it's not part of the String but part of the String array declaration syntax,just split it with a -
String[] arr = {"aa-bb-cc","dd-bb-ee","aa-hh-gg"};
for(int i=0;i<arr.length;i++){
newArr = arr[i].split("-");
appList.add(newArr[0]);
prodList.add(newArr[1]);
rolList.add(newArr[2]);
}

String into char on 2D array (java)

I am trying to fill a 2D char array with 5 words. Each string must be split into single characters and fill one row of the array.
String str = "hello";
char[][] words = new char[10][5];
words[][] = str.toCharArray();
My error is at the 3rd line I don't know how to split the string "hello" into chars and fill only the 1st row of the 2-dimensional array
If you want the array to fill the first row, just asign it to the first row:
words[0] = str.toCharArray();
Since this will create a new array in the array, you should change the instantiation of words to this:
char[][] words = new char[5][];
Java has a String class. Make use of it.
Very little is known of what you want with it. But it also has a List class which I'd recommend as well. For this case, I'd recommend the ArrayList implementation.
Now onto the problem at hand, how would this code look now?
List<String> words = new ArrayList<>();
words.add("hello");
words.add("hello2");
words.add("hello3");
words.add("hello4");
words.add("hello5");
for (String s : words) {
System.out.println(s);
}
For your case if you are stuck with using arrays.
String str="hello";
char[][] words = new char[5][];
words[][] = str.toCharArray();
Use something along the line of
String str = "hello";
char[][] words = new char[5][];
words[0] = str.toCharArray();
for (int i = 0; i < 5; i++) {
System.out.println(words[i]);
}
However, why invent the wheel again? There are cases however, more can be read on the subject here.
Array versus List<T>: When to use which?

How to Split an ArrayList in Android Using JAVA?

Here is the code to put values in ArrayList and I am unable to split the arraylist with ",". Can someone please help me as to how to achieve this task ?
spinnerArrayList = new ArrayList<String>();
spinnerArrayList.add(menuFieldInstance.getFieldValues());
Log.i("spinnerArrayList",""+spinnerArrayList);
//for(int j=0;j<spinnerArrayList.size();j++)
//{
Log.i("spinnerArrayList after splitting ,",""+spinnerArrayList.get(0).split(","));
//}
Here is the Logcat of Spinner ArrayList and SpinnerArrayList after splitting.............
02-10 22:00:48.285: I/spinnerArrayList(19378): [0100~Avon & Somerset,0200~Bedfordshire,0300~Cambridgeshire,0400~Cheshire,0500~City of London,0600~Cleveland,0700~Cumbria,0800~Derbyshire,0900~Devon & Cornwall,1000~Dorset,1100~Durham,1200~Essex,1300~Gloucestershire,1400~Greater Manchester,1500~Hampshire,1600~Hertfordshire,1700~Humberside,1800~Kent,1900~Lancashire,2000~Leicestershire,2100~Linconshire,2200~Merseyside,2300~Metropolitan,2400~Norfolk,2500~Northamptonshire,2600~Northumbria,2700~North Yorkshire,2800~Nottinghamshire,2900~South Yorkshire,3000~Staffordshire,3100~Suffolk,3200~Surrey,3300~Sussex,3400~Thames Valley,3500~Warwickshire,3600~West Mercia,3700~West Midlands,3800~West Yorkshire,3900~Wiltshire,4000~Dyfed,4100~Gwent,4200~North Wales,4300~South Wales,4400~Royal Ulster,4500~Strathclyde,4600~Central Scotland,4700~Dumfries and Galloway,4800~Fife,4900~Grampian,5000~Lothian and Borders,5100~Northern Scotland,5200~Tayside,5300~Gurnsey,5400~States of Jersey,5500~Isle of Man,NO~No Police Response,THAM~THAMES VALLEY,WEST~WEST MIDLANDS POLICE,5600~Buckinghamshire]
02-10 22:00:48.285: I/spinnerArrayList after splitting ,(19378): [Ljava.lang.String;#41b9a498
// try to print this way then you getting actual value at index becz your try to print String[] object rather each index value so do this way
spinnerArrayList = new ArrayList<String>();
spinnerArrayList.add("");
for (int i=0;i<spinnerArrayList.size();i++){
String[] splitedValue = spinnerArrayList.get(i).split(",");
for (int j=0;j<splitedValue.length;j++){
Log.i(i+" at ArrayIndex "+j+" at splitedIndex Value is >> ",splitedValue[j]);
String[] splitedValue1 = splitedValue[j].split("~");
if(splitedValue1.length==1){
continue;
}
for (int k=0;k<splitedValue1.length;k++){
Log.i(j+" at splitedIndex "+k+" at splited1Index Value is >> ",splitedValue1[k]);
}
}
}
You can't split ArrayList. You can split String, e.g "I am some String, you can split me".split(",") will return an array of 2 Strings, but ArrayList is a data structure which holds some Strings and it doesn't mean that they are separated with comma. You can try to split each item of the list, e.g.
for (String s : spinnerArrayList) {
String[] res = s.split(",");
// do smth with res
}
spinnerArrayList.get(0).split(",") doesn't split "the arrayList" it splits the string at index zero, and since the returned result is an array of strings - you can't concatenate it using the + operator to another string:
Log.i("spinnerArrayList after splitting ,",""+spinnerArrayList.get(0).split(","));
Read the splitted string into a String array first:
String[] arr = spinnerArrayList.get(0).split(",");
and then loop the array and print the values"
for(String val: arr){
Log.i(val);
}

Convert String elements to Array

I have a String :
str="[a],[b],[c]";
How can I convert str to array in Java (Android):
array[0] -> a
array[1] -> b
array[2] -> c
EDIT:
and what about multidimensinal array? str="[["a1","a2","a3"],["b1","b2","b3"]]";
try
String str="[a],[b],[c]";
str= str.replaceAll("\\]|\\[", "");
String[] arr= str.split(",");
===========================================
update
converting multi dimension array to single dimension is already answered in SO please check change multidimensional array to single array
just copied the solution
public static String[] flatten(String[][] data) {
List<String> toReturn = new ArrayList<String>();
for (String[] sublist : Arrays.asList(data)) {
for (String elem : sublist) {
toReturn.add(elem);
}
}
return toReturn.toArray(new String[0]);
}
You can use following way.
String Vstr = "[a],[b],[c]";
String[] array = Vstr.replaceAll("\\]|\\[", "").split(",");
You would need to process your string and build your array. You could either take a look at .split(String regex) (which might require you to do some more processing to clean the string) or else, use a regular expression and do as follows:
Use a regex like so: \[([^]]+?)\]. This will seek out characters in between square brackets and put them into a group.
Use the .find() method available from the Matcher class and iterate over the matches. Put everything into a list so that you can put in as many hits as you need.
If you really need the result to be in an array, use the .toArray() method.
Take a look at String.split() method
An alternative to the regex and what npinti, i think, is talking about:
String myStrg = "[a],[b],[c]";
int numCommas = 0;
for( int i = 0; i < myStrg.length(); i++ )
{
// Count commas
if( myStrg.charAt(i) == ',' )
{
numCommas++;
}
}
// Initialize array
myArry = new String[numCommas];
myArry = myStrg.split(",");
// Loop through and print contents of array
for( String arryStrg: myArry )
{
System.out.println( arryStrg );
}
Try this code.
String str="[a],[b],[c]";
str= str.replaceAll("\\]|\\[", "");
String[] arr= str.split(",");

how do I ignore/delete values of an array in java

I have a list of words , there are 4 words, it cant contain more that 4 its just an example. I want to use just 2 of the words the rest of them should be ignored or deleted e.g :
String planets = "Moon,Sun,Jupiter,Mars";
String[] planetsArray = planets.split(",");
int numberOfPlanets = planetsArray.length;
the result i get is 4. How do i delete the rest of the words if my list contains more that 2 words ?
As suggested in your previous question, you can use
String[] fewPlanets = new String[]{planets[0], planets[1]};
Just make sure the planets array has 2 elements or more to avoid an ArrayIndexOutOfBoundsException. You can use length to check it: if (planets.length >= 2)
For a more sophisticated solution, you could also do this using System.arrayCopy() if you're using Java 1.5 or earlier,
int numberOfElements = 2;
String[] fewPlanets = new String[2];
System.arraycopy(planets, 0, fewPlanets, 0, numberOfElements);
or Arrays.copyOf() if you're using Java 1.6 or later:
int numberOfElements = 2;
String[] fewPlanets = Arrays.copyOf(planets, numberOfElements);
String planets = "Moon,Sun,Jupiter,Mars";
String[] planetsArray = planets.split(",");
if(planetsArray .length > 2){
String []newArr = new String[2];
newArr[0]=planetsArray [0];
newArr[1]=planetsArray [2];
planetsArray = newArr ;
}
Use Arrays.asList to get a List of Strings from String[] planetsArray.
Then use the methods of the List interface -contains,remove,add, ...- to simply do whatever you want on that List.
If you need to select the first 2 planets just copy the array:
String[] newPlanetsArray = Arrays.CopyOf(planetsArray, 2);
If you need to select 2 specific planets you can apply the following algorithm:
First, create a new array with 2 elements. Then, iterate through the elements in the original array and if the current element is a match add it to the new array (keep track of the current position in the new array to add the next element).
String[] newPlanetsArray = new String[2];
for(int i = 0, int j = 0; i < planetsArray.length; i++) {
if (planetsArray[i].equals("Jupiter") || planetsArray[i].equals("Mars")) {
newPlanetsArray[j++] = planetsArray[i];
if (j > 1)
break;
}
}
You could use an idea from How to find nth occurrence of character in a string? and avoid reading the remaining values from your comma separated string input. Simply locate the second comma and substring upto there
(Of course if your code snippet is just an example and you do not have a comma separated input, then please ignore this suggestion :)

Categories