item1:100
item2:50
item3:200
I want to store separate item and price and store them in two different arrays: like in one array ,
item1
item2
item3
and in another array
100
50
200
item1:100
item2:50
item3:200
I want to store separate item and price and store them in two different arrays: like in one array ,
item1
item2
item3
and in another array
100
50
200
You can try the following code:
String DELIMITER = ":";
ArrayList<String> arrItems = new ArrayList<String>();
ArrayList<Integer> arrPrices = new ArrayList<Integer>();
Then you can just split the string and store the relevant values in the arraylist as:
String[] strTemp = "item1:100".split(DELIMITER);
arrItems.put(strTemp[0]);
arrPirces.put(strTemp[1]);
You can use split
to separate a string based on another string (actually a regular expression):
String str = "item1:100";
String[] words = str.split (":");
From there, it's a simple matter of adding words[0]
to one array and words[1]
to the other.
The following complete program shows how it's done:
import java.util.ArrayList;
class Test {
private static ArrayList<String> items = new ArrayList<String>();
private static ArrayList<Integer> values = new ArrayList<Integer>();
private static void addToArray (String str) {
String[] words = str.split(":");
items.add(words[0]);
values.add(new Integer (words[1]));
}
public static void main(String[] args) {
addToArray ("item1:100");
addToArray ("item2:50");
addToArray ("item3:200");
for (int i = 0; i < items.size(); i++)
System.out.println ("Item = " + items.get(i) +
", value = " + values.get(i));
}
}
The output:
Item = item1, value = 100
Item = item2, value = 50
Item = item3, value = 200
Keep in mind I'm just doing simplistic string splitting here with no error handling code - you may want to add that if you value robust code, particularly if there's a possibility your input data may not be valid (eg, "item4:hello"
will generate a java.lang.NumberFormatException
).
You can use StringTokenizer
class for your requirement.
StringTokenizer st = new StringTokenizer(yourString, ":");
arrayOne[0] = st.nextToken();
arrayTwo[0] = st.nextToken();
You can use split()
method for string.
String[] temp = yourString.split(":");
Try this.
Java provides the split function in strings. str.split(":")
for "item:100" returns a String[] with the elements {"item1","100}
. Now just iterate through the split arrays and build a combined array of the two parts.
Source: http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#split(java.lang.String)