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);
}
Related
I am getting data from a Bluetooth characteristic in bytes and converting it into an array of floats that look like this:
[318.0159, 331.81818, 324.71603, 348.4345, 323.108, 3.2360008]
I want to be able to split this data into 6 strings,
"318.0159" "331.81818" "324.71603" "348.4345" "323.108" "3.2360008".
I have already tried to do this:
EDIT(charData initialized like so):
final StringBuilder stringBuilder = new StringBuilder(bytes.length);
for (byte byteChar : bytes)
stringBuilder.append(String.format("%02X ", byteChar));
String charData = stringBuilder.toString();
String[] data = charData.split(",");
System.out.println(data[1]);
System.out.println(data[2]);
System.out.println(data[3]);
System.out.println(data[4]);
System.out.println(data[5]);
System.out.println(data[6]);
but when it tries to print the first data point, I get the exception:
Unhandled exception in callback
java.lang.ArrayIndexOutOfBoundsException: length=1; index=1
Thanks in advance for the help!!
You need remove [ and ] first, and the array index ranges [0, 5]:
String charData = "[318.0159, 331.81818, 324.71603, 348.4345, 323.108, 3.2360008]";
charData = charData.replace("[", "").replace("]", "");
String[] data = charData.split(",");
System.out.println(data[0]);
System.out.println(data[1]);
System.out.println(data[2]);
System.out.println(data[3]);
System.out.println(data[4]);
System.out.println(data[5]);
output:
318.0159
331.81818
324.71603
348.4345
323.108
3.2360008
To avoid the leading white spaces, you can split with regex:
String[] data = charData.split(",\\s*");
output:
318.0159
331.81818
324.71603
348.4345
323.108
3.2360008
Sun's answer is spot on, I prefer to trim input as well:
charData= charData.replace("[", "").replace("]", "");
String[] data = charData.split(",");
for(int x=0;x<=data.length;x++){
String data_cleaned = data[x].trim();
System.out.println(data_cleaned);
}
try this
String[] data = ["318.0159", "331.81818", "324.71603", "348.4345", "323.108", "3.2360008"]
for (int i = 0; i < data.size(); i++) {
System.out.println(data[i]);
}
ArrayIndexOutOfBoundsException occurs when you access some sort of array but the index is not available. also remember that an array starts from 0
It seems your charData don't have any data, It is not same as you have asked in querstion.
Please print the data before split()
Also check data in bytes before your for (byte byteChar : bytes)
Also it is not the issue of array index o to 5 as others suggested, other wise error would have been java.lang.ArrayIndexOutOfBoundsException: index=6
I have a String array which contains both integer and non-integer elements, and I need to remove all the non-integer elements of that array.
Now I am only able to remove the non-integer content in a single string, but I need to remove the entire non-integer elements in an array.
My snippet as follows
String str = "a12.334tyz.78x";
str = str.replaceAll("[^\\d.]", "");
Can anyone help me to achieve it?
You can achieve it by below code
Pattern p = Pattern.compile("\\d*");
String [] array=new String[]{"23","33.23","4d","ff"};
List<String> lst=new ArrayList<String>();
for (int i=0; i<array.length; i++) {
if(p.matcher(array[i]).matches()){
lst.add(array[i]);
}
}
System.out.println(""+lst);
Your original code is this:
String str = "a12.334tyz.78x";
str = str.replaceAll("[^\\d.]", "");
First, if you need to remove all non-integer character, you need to change your regex from "[^\d.]" to "[^\d]".
Yours will not remove dots character.
Then, you said:
Now I am only able to remove the non-integer content in a single
string, but I need to remove the entire non-integer elements in an
array.
Maybe I'm not getting this right, but isn't just a matter of looping while doing the same thing ? You didn't show us any code with loops, but perhaps your true problem is reassigning the modified value to the array ?
try this:
for(int i=0;i<strArray.length;i++){
strArray[i] = strArray[i].replaceAll("[^\\d]", "");
}
MAYBE you were doing something like this ? (this does not work):
for(String str: strArray){
str = str.replaceAll("[^\\d]", "");
}
That doesn't work because the modified string is not reassigned to the array, it is assigned to the new variable 'str'. So this code does not update the value pointed by the array.
replace all numbers - str = str.replaceAll("\\d", "");
replace all non-numbers - str = str.replaceAll("[^\\d]", "");
to do so in an array, iterate over the Array and do the replacment.
To remove all the non-integer values form a string you can try the following:
public boolean isInt(String s)
{
for(int i = 0; i < s.length(); i++)
{
try
{
Integer.parseInt(String.valueOf(s.charAt(i)));
}catch(NumberFormatException e)
{
return false;
}
}
return true;
}
Then you can iterate your array and remove the non-integer elements like this
for(int i = 0; i < arr.length; i++)
{
if(isInt(arr[i]))//remove the element
}
It would probably be easier to remove elements from a list than from an array. However, you can stream the elements of the array, remove invalid elements with flatMap, and then convert back to an array.
When using flatMap, each element in the input can produce zero, one, or many elements in the output, so we map the valid ones to singleton streams containing just that element, and the invalid ones to empty streams, thus removing them from the result.
String[] result = Arrays.stream(input)
.flatMap(a -> Pattern.matches("\\d+", a)?
Stream.of(a) : Stream.empty())
.toArray(String[]::new);
If your regex is working correctly, you already solved most of your problem. You only need to use your code in a for loop. You can try the code below:
public String[] removeNonIntegersFromArray(String[] array){
ArrayList<String> temp = new ArrayList<String>();
for (int i=0; i<array.length; i++) {
String str = array[i];
if(!str.matches(".*[^\\d]+.*")){
temp.add(str);
}
}
String[] result = new String[temp.size()];
result = (String[]) temp.toArray(new String[temp.size()]);
return result;
}
Edit: I refactored the code as it will delete whole array element which has non-integer.
Here is an idea,
Instead of replacing all non-int number, to find all integer and add them to a new string.
for(int i=0;i<str.length();i++)
{
if(Character.isDigit(str.charAt(i)))
new_str.append(str.charAt(i));
}
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));
I want to evaluate String like "[1,5] [4,5] [10,6]" in in array.
I'm not quite familiar with the Java regex and the syntax.
String game = "[1,5] [4,5] [10,6]"
Pattern splitter = Pattern.compile("\\[|,|\\]");
splitter.matcher(game);
public String [] gameArray = null;
gameArray = splitter.split(game);
I want to to iterate over each pair of array such as : [0][0] => 1; [0][1] => 5
If you put
StringTokenizer st = new StringTokenizer(game, "[,] ");
while (st.hasMoreTokens())
{
currentNumber = Integer.parseInt(st.nextToken());
// fill array with it
}
It should be what you need, if I understood well
For this purpose you need to split your string.
first of all you need to split on space and after that you need to split on ,(comma).and your third step will be remove brackets So at the end you will get you string into array.
Try,
String game = "[1,5] [4,5] [10,6]";
String[] arry=game.substring(1, game.length()-1).split("\\] +\\[");
List<String[]> twoDim=new ArrayList<>();
for (String string : arry) {
String[] twoArr=string.split(",");
twoDim.add(twoArr);
}
String[][] twoArr=twoDim.toArray(new String[0][0]);
System.out.println(twoArr[0][0]); // 1
System.out.println(twoArr[0][1]); // 5
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(",");