Reputation: 57
I am trying to read this line in Java - "abc:300:xyz:def", and I'm really unsure how to do this using arrays because in the array format it would be like this: ["abc:300:xyz:def"] . I started with
ArrayList<String> list = new ArrayList<String>();
list.add("abc");
list.add("300");
list.add("xyz");
list.add("def");
in my constructor, but then I don't know if I add a
list.split(":")
somewhere, because if so would that be right after I initialize the ArrayList? Any help would be appreciated!
Upvotes: 0
Views: 103
Reputation: 21
If you are looking only the arrays not the arraylist, you can just use the split method from the string
String line = "abc:300:xyz:def";
String[] stringArray = line.split(":");
Upvotes: 0
Reputation: 1866
Do this:
String line = "abc:300:xyz:def";
List<String> list = Arrays.asList(line.split(":"));
Now you have a list containing the 4 strings.
Upvotes: 1
Reputation: 5940
To join the items, use String.join
ArrayList<String> list = new ArrayList<>();
list.add("abc");
list.add("300");
list.add("xyz");
list.add("def");
String str = String.join(":", list);
To split the items, use String.split
ArrayList<String> list = Arrays.asList(str.split(":"));
Upvotes: 2
Reputation: 722
If you have to read a line from console you can try something like this
Scanner scanner = new Scanner(System.in);
String yourString = scanner.next();
StringTokenizer st = new StringTokenizer(yourString , ":");
while (st.hasMoreElements()) {
System.out.println(st.nextElement());
}
Upvotes: 0