How to split an array of strings into multiple strings? - java

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

Related

Java help regarding of arrays and printing out the individual lengths in the arrays

Currently, I have trouble attempting to print out the individual lengths efficiently.
String[] array = {"test", "testing", "tests"};
int arraylength = array[0].length();
System.out.println(arraylength);
Now, this does work in printing out the length however, it is inefficient and doesn't work if theoretically I don't know the length of the array.
Thanks for your input and I would appreciate if the code insisted contains "System.out.println" included so I don't have trouble figuring out which to print out.
Use this:
String[] array = {"test", "testing", "tests"};
for(String str : array) {
System.out.println(str.length());
}
If you are using Java 8 then it's a one liner :)
Arrays.asList(array).forEach(element -> System.out.println(element.length()));
What you are doing is, converting your array to a list and then running a for loop over it. Then for every element, you are printing out the length of the element.
EDIT
From one of the comment, this is even a better version of my code.
Arrays.stream(array).map(String::length).forEach(System.out::println);
Here first you convert your array to a list and then map each element to the function length of string class, then you run a foreach over it which prints out the mapped values.
String[] array = {"test", "testing", "tests"};
The length for array is:
int arraylength = array.length;
To have retrieve length for string:
for(String string: array) {
System.out.println(string.length());
}

Given a String how to convert it to an Array: Java

so I'm pretty new at Java and StackOverflow (That's what they all say) and I am stuck at the given problem:
My method is given a String e.g.: "[ 25 , 25 , 125 , 125]". Now the method should return an Array of integers representation of the String provided, that is: it should return
[25,25,125,125].
Here is a segment of my method. Note: input is the String provided
if(input.charAt(index) == '['){
index++;
int start = index;
while(index <= input.length() && input.charAt(index) != ']'){
index++;
}
String[] arrayStr = input.substring(start, index).split(",");
int[] arrayInt = new int[4];
for (int i = 0; i < arrayStr.length; i++){
arrayInt[i] = Integer.parseInt(arrayStr[i]);
}
return arrayInt;
My code works if input is: "[25,25,125,125]" (If there are no spaces between the numbers).
However if there are spaces between the numbers then my code doesn't work and I understand why, but I am struggling to find a way to solve this problem. Any help will be appreciated.
Spaces will fail with Integer.parseInt(arrayStr[i]) (e.g. the string "25 " is not a valid number as it contains a space. (parseInt will throw an exception in such cases.)
However you can solve it quickly by trimming your array elements:
Integer.parseInt(arrayStr[i].trim())
trim() returns a copy of the string without leading/trailing white space
You can replace the space with empty in the string
input=input.replace(" ","")
You can
remove [ and ] and all spaces
split on , to get all tokens
iterate over all tokens
parse string number to int
add parsed int to result array
So your code can look like
String data = "[ 25 , 25 , 125 , 125]";
String[] tokens = data.replaceAll("\\[|\\]|\\s", "").split(",");
int[] array = new int[tokens.length];
for (int i=0; i<tokens.length; i++){
array[i]=Integer.parseInt(tokens[i]);
}
Or if you have Java 8 you can use streams like
int[] array = Stream.of(data.replaceAll("\\[|\\]|\\s", "").split(","))
.mapToInt(number -> Integer.parseInt(number))
.toArray();

Java, How to convert a string into an Array

I've got a string, for example:
String code = new String("[199, 56, 120]")
My goal is to create and Array that contains only the numbers inside the [] and beetween commas;
In this case it would be for example:
array[0] = 199
array[1] = 56
array[2] = 120
Is possible to do something like this??
Thanks in advance.
You just need to use the split function.
Skip the [ and the ] and you can do something like this:
String input = "199 56 120";
String[] array = input.split(" ");
If you really want [ and the ] then you can use something like
input.replace("[", "");
input.replace("]", "");
To strip the string before you split it.
Edit
It doesn't matter what the format is or what the numbers are or how many they are, you simply edit the split definition according to the format, so if you're case is , then you simply use that as the split parameter.
String input = "[number, number, number]";
String sep = ", ";
String fixedInput = input.replace("[", "").replace("]", "");
String[] array = fixedInput.split(sep);
// array[0] contains first number.
// array[1] contains second number.
If you want an int[] array then you could do something like this:
int[] intArray = new int[array.length];
for(int i = 0; i < array.length; i++)
{
intArray[i] = Integer.parseInt(array[i]);
}
If you want a one-line solution:
String[] array = code.replaceAll("[^\\d ]", "").split(" ");
The in-line call to replaceAll() removes non-digits/spaces.

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);
}

Exporting specific pattern of string using split method in a most efficient way

I want to export pattern of bit stream in a String varilable. Assume our bit stream is something like bitStream="111000001010000100001111". I am looking for a Java code to save this bit stream in a specific array (assume bitArray) in a way that all continous "0"s or "1"s be saved in one array element. In this example output would be somethins like this:
bitArray[0]="111"
bitArray[1]="00000"
bitArray[2]="1"
bitArray[3]="0"
bitArray[4]="1"
bitArray[5]="0000"
bitArray[6]="1"
bitArray[7]="0000"
bitArray[8]="1111"
I want to using bitArray to calculate the number of bit which is stored in each continous stream. For example in this case the final output would be, "3,5,1,1,1,4,1,4,4". I figure it out that probably "split" method would solve this for me. But I dont know what splitting pattern would do that for me, if i Using bitStream.split("1+") it would split on contious "1" pattern, if i using bitStream.split("0+") it will do that base on continous"0" but how it could be based on both?
Mathew suggested this solution and it works:
var wholeString = "111000001010000100001111";
wholeString = wholeString.replace('10', '1,0');
wholeString = wholeString.replace('01', '0,1');
stringSplit = wholeString.split(',');
My question is "Is this solution the most efficient one?"
Try replacing any occurrence of "01" and "10" with "0,1" and "1,0" respectively. Then once you've injected the commas, split the string using the comma as the delimiting character.
String wholeString = "111000001010000100001111"
wholeString = wholeString.replace("10", "1,0");
wholeString = wholeString.replace("01", "0,1");
String stringSplit[] = wholeString.split(",");
You can do this with a simple regular expression. It matches 1s and 0s and will return each in the order they occur in the stream. How you store or manipulate the results is up to you. Here is some example code.
String testString = "111000001010000100001111";
Pattern pattern = Pattern.compile("1+|0+");
Matcher matcher = pattern.matcher(testString);
while (matcher.find())
{
System.out.print(matcher.group().length());
System.out.print(" ");
}
This will result in the following output:
3 5 1 1 1 4 1 4 4
One option for storing the results is to put them in an ArrayList<Integer>
Since the OP wanted most efficient, I did some tests to see how long each answer takes to iterate over a large stream 10000 times and came up with the following results. In each test the times were different but the order of fastest to slowest remained the same. I know tick performance testing has it's issues like not accounting for system load but I just wanted a quick test.
My answer completed in 1145 ms
Alessio's answer completed in 1202 ms
Matthew Lee Keith's answer completed in 2002 ms
Evgeniy Dorofeev's answer completed in 2556 ms
Hope this helps
I won't give you a code, but I'll guide you to a possible solution:
Construct an ArrayList<Integer>, iterate on the array of bits, as long as you have 1's, increment a counter and as soon as you have 0, add the counter to the ArrayList. After this procedure, you'll have an ArrayList that contain numbers, etc: [1,2,2,3,4] - Representing a serieses of 1's and 0's.
This will represent the sequences of 1's and 0's. Then you construct an array of the size of the ArrayList, and fill it accordingly.
The time complexity is O(n) because you need to iterate on the array only once.
This code works for any String and patterns, not only 1s and 0s. Iterate char by char, and if the current char is equal to the previous one, append the last char to the last element of the List, otherwise create a new element in the list.
public List<String> getArray(String input){
List<String> output = new ArrayList<String>();
if(input==null || input.length==0) return output;
int count = 0;
char [] inputA = input.toCharArray();
output.add(inputA[0]+"");
for(int i = 1; i <inputA.length;i++){
if(inputA[i]==inputA[i-1]){
String current = output.get(count)+inputA[i];
output.remove(count);
output.add(current);
}
else{
output.add(inputA[i]+"");
count++;
}
}
return output;
}
try this
String[] a = s.replaceAll("(.)(?!\\1)", "$1,").split(",");
I tried to implement #Maroun Maroun solution.
public static void main(String args[]){
long start = System.currentTimeMillis();
String bitStream ="0111000001010000100001111";
int length = bitStream.length();
char base = bitStream.charAt(0);
ArrayList<Integer> counts = new ArrayList<Integer>();
int count = -1;
char currChar = ' ';
for (int i=0;i<length;i++){
currChar = bitStream.charAt(i);
if (currChar == base){
count++;
}else {
base = currChar;
counts.add(count+1);
count = 0;
}
}
counts.add(count+1);
System.out.println("Time taken :" + (System.currentTimeMillis()-start ) +"ms");
System.out.println(counts.toString());
}
I believe it is more effecient way, as he said it is O(n) , you are iterating only once. Since the goal to get the count only not to store it as array. i woul recommen this. Even if we use Regular Expression ( internal it would have to iterate any way )
Result out put is
Time taken :0ms
[1, 3, 5, 1, 1, 1, 4, 1, 4, 4]
Try this one:
String[] parts = input.split("(?<=1)(?=0)|(?<=0)(?=1)");
See in action here: http://rubular.com/r/qyyfHNAo0T

Categories