I want to convert a string with integers to array with integers in Java. How i can do this?I have an array with strings.Every string is integers. I want to access every string with a click from a button.
String[] INT_ARRAY={
//0
"250,125,20,20,20,40,20,20,20,40,20,20,20,2500",
//1
"233,63,28,63,29,63,28,16,28,17,26,63,29,17,26,16....
........
}
public void onClick(View v) {
counter++;
String IntString = INT_ARRAY[counter];
String[] parts = IntString.split(",");
final int[] A = new int[parts.length()];
for(int i=0; i<parts.length(); i++){
A[i] = Integer.parseInt(parts(i));
Toast.makeText(getApplicationContext(),String.valueOf(A[i]), Toast.LENGTH_SHORT).show();
}
}
You need String#spilt()
to split the string, something like:
String[] parts = "aa,bb,cc,dd".split(",");
parts
now consists of {"aa", "bb", "cc", "dd"}
.
Then use the enhanced-for loop to iterate over each part, something like:
for(String part : parts) Log.d("", part);
So you have a partially-serialized representation of what appears to be an array of integer arrays. From your code, you obviously understand that you need to use parseInt()
to convert a string representation of an integer to an int
primitive. This part looks good, but you need logic to loop through each comma-separated value in each string. You can use the split()
method to create an array of strings from your comma separated list. The entire solution would look like the following:
public void onClick(View v) {
counter++;
String IntString = INT_ARRAY[counter];
final String[] vals = IntString.split(","); // Here we split the comma-separated string
final int[] A = new int[vals.length];
for(int i=0; i<vals.length; i++){
A[i] = Integer.parseInt(vals[i]);
Toast.makeText(getApplicationContext(),String.valueOf(A[i]), Toast.LENGTH_SHORT).show();
}
}
private Integer[] splitIntegers(String s){
Object[] numbersAsString = s.split(",");
return Arrays.copyOf(numbersAsString, numbersAsString.length, Integer[].class);
}
Calling:
for(String s: INT_ARRAY){
Integer[] ints = splitIntegers(s);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.