Reputation: 919
I have a String
String test = "7462356098660AE";
I want to split it into:
test1 = "746";
test2 = "2356";
test3 = "0986";
test4 = "60AE";
The length of the String test
will be always the same.
How will I be able to do this?
PS: I have checked other questions but couldn't find a suitable answer.
Upvotes: 1
Views: 7325
Reputation: 200226
For convenience, you can write this kind of Splitter class:
public class Splitter {
private final int[] borders;
private final String s;
public Splitter(String s, int... borders) {
this.s = s;
this.borders = borders;
}
public String seg(int seg) {
return s.substring(seg == 0? 0 : borders[seg-1], borders[seg]);
}
}
You'd use it like this:
final Splitter splitter = new Splitter("7462356098660AE", 3, 7, 11, 15);
for (int i = 0; i < 4; i++) System.out.println(splitter.seg(i));
Upvotes: 4
Reputation: 1107
Not sure what your use case is here, but if the substring of code are always the same length, you could use the substring()
method. You just give it the beginning and ending index of the substring you want.
Upvotes: 2
Reputation: 10524
String test = "7462356098660AE";
String test1 = test.substring(0,3);
String test2 = test.substring(3,7);
String test3 = test.substring(7,11);
String test4 = test.substring(11,15);
Upvotes: 6
Reputation: 613
If the string is fixed width for all of the fields you want, you could use the substring/subSequence methods of String, or your could create regular expression and grabs the values of the capturing groups.
Upvotes: 1