April 29th, 2003, 05:18 PM
-
extracting int from string
Hi im tryin to extract int values from a StringBuffer looking something like this for instance:
"|5|56|789|4|21"
would this code work?
-----------------------------------------------------------------
//Buff is the StringBuffer where the string is stored
int start=0;
int end=0;
int invalues[]=new int[5];
for(int i=0; i<invalues.length; i++) {
start=buff.indexOf("|",start);
end=buff.indexOf("|",start);
String mini=buff.substring((start+1),end);
int convInt= new Integer(mini).intValue();
invalues[i]=convInt;
}
----------------------------------------------------------------------
April 30th, 2003, 01:18 AM
-
Why dont you just use StringTokenizer???
-
Originally posted by Pixel_Damage
Why dont you just use StringTokenizer???
because i dont know how to use it and im in a hurry!
however my question was if the code i wrote would work properly and i would apriciate if someone would correct it
-
maybe that way?
First, why are you askin if this code would work? Just test it.
Well, I just played a littlebit with your code and thats my result
PHP Code:
StringBuffer buff = new StringBuffer().append("|5|56|789|4|21|");
int invalues[]=new int[5];
int start=0;
int end=0;
for(int i=0; i<invalues.length; i++)
{
start = buff.indexOf("|",end);
end = buff.indexOf("|",start+1);
String mini = buff.substring((start+1),end);
int convInt = Integer.parseInt(mini);
invalues[i]=convInt;
}
Note that I have added an | at the end of the buffer to prevent a -1 for the last value of end.
I guess you ar using Java 1.4 because you are using StringBuffer.indexOf so why don't you String.split ?
Have a nice day,
FReAK
-
heh , i was in a hurry too , for something similar ...
it took about 5 minutes through a book , thanks a lot pixel
-
O.k., you said you're in a hurry, but if you instead want to use StringTokenizer, try this:
Code:
StringTokenizer tok = new StringTokenizer(buff, "|");
int i=0;
int intvalues[] = new int[5];
while(tok.hasMoreTokens() {
intvalues[i]=Integer.parseInt(tok.nextToken());
i++;
}