I want to convert below code to store the split string in string array without using String.split() because i am working on legacy java 1.2 in our production environment
String strings ="1,2,3,4;5,6,7,8";
String[] output= strings.split(";");
How to achieve this?
Use StringTokenizer
, the javadoc it has been around since version 1.
Just do
StringTokenizer strTokenizer = new StringTokenizer("1,2,3,4;5,6,7,8", ";");
and iterate while strTokenizer.hasMoreElements()
.
You have to use StringTokenizer
since StringTokenizer
available since JDK 1.0
. You better to change your JDK
in production too.
StringTokenizer stringTokenizer=new StringTokenizer("1,2,3,4;5,6,7,8",",;");
String[] arr=new String[stringTokenizer.countTokens()];
int i=0;
while (stringTokenizer.hasMoreTokens()){
arr[i]=stringTokenizer.nextToken();
i++;
}
String strings ="1,2,3,4;5,6,7,8";
StringTokenizer tok = new StringTokenizer(strings, ";,");
String[] coordinates = new String[tok.countTokens()];
int j = 0;
while (tok.hasMoreTokens()) {
coordinates[j++] = tok.nextToken();
}
System.out.println(Arrays.toString(coordinates));
[1, 2, 3, 4, 5, 6, 7, 8]
You can specify the delimiters. If you only ;
for instance.
Not familiar with 1.2 limitations... you may do it manually: first, count the ';' occurences so you can create your coordinates array, then use available String
methods to go through your original string and concatenate the result and stop every ';'
You can use the Scanner class for the same purpose.
String s="1,2,3,4;5,6,7,8";
Scanner sc=new Scanner(s).useDelimiter(";");
while(sc.hasNext())
{
System.out.println(sc.next());
}
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.