I want to know how to convert a string into an integer. I feel that i can type cast the
string but if any one can help me the code I will be grateful
Thanks
Siva
Silva, I ran into a similar problem but I was reading from a file. I wrote a small program to convert a string to a character array. However, when you do this, the numbers you get are something like 49 greater. Take a look at this:
public int change_string_to_int(String loader_string) {
int load_int = 0;
char[] edgeArray_char;
char singlechar1;
char singlechar2;
char singlechar3;
char singlechar4;
edgeArray_char = loader_string.toCharArray();
if(edgeArray_char.length == 1){
singlechar3 = edgeArray_char[0];
load_int = (int)singlechar3;
load_int = load_int - 48;
}
else if(edgeArray_char.length == 2){
singlechar2 = edgeArray_char[0];
singlechar3 = edgeArray_char[1];
load_int = (((int)singlechar2) - 48)*10 + (((int)singlechar3) - 48) ;
}
else if(edgeArray_char.length == 3){
singlechar1 = edgeArray_char[0];
singlechar2 = edgeArray_char[1];
singlechar3 = edgeArray_char[2];
load_int = (((int)singlechar1) - 48)*100 + (((int)singlechar2) - 48)*10 + (((int)singlechar3) - 48) ;
}
else if(edgeArray_char.length == 4){
singlechar1 = edgeArray_char[0];
singlechar2 = edgeArray_char[1];
singlechar3 = edgeArray_char[2];
singlechar4 = edgeArray_char[3];
load_int = (((int)singlechar1) - 48)*1000 + (((int)singlechar2) - 48)*100 + (((int)singlechar3) - 48)*10 + (((int)singlechar4)
- 48) ;
}
return load_int;
}
It loads a string and returns an int but only upto 4 digets. You may have to modify it. I'm sure this is not the easiest way but it works so you may want to try it.
Sincerely,
Shari
Not that Shari's implementation isn't fine (I really didn't read it thoroughly) There's no way to convert a string (longer than a few characters into an integer due to limits on the size of integers)
but here's a fairly simple method:
import java.math.BigInteger;
class myProg
{
.
.
.
public BigInteger cnvToBigIntFromString
(
String strIn
}
{
private static final int SIZEoFnUMbLOCKS = 3;
String strTempAns = "";
int iIntVal;
String strIntVal;
String strNewIntVal;
String strPad = "";
for (i = 0; i {
iIntVal = (int) strIn.charAt(i);
/* this section makes it easy to
convert the numeric representation
back into a string by making sure
each latter is converted into
"SIZEoFnUMbLOCKS"-digits by padding
with leading zeroes if necessary,
otherwise it would be very difficult to
convert the numbers back into a string
(which I'm assuming that some part
of your program does)
*/
strIntVal = new String(iIntVal);
for (j=strIntVal.length;
strIntVal < SIZEoFnUMbLOCKS;
strIntVal++)
{
strPad += "0";
}
strTempAns = strTempAns + strPad
+ strIntVal;
}
return (new BigInteger(strTempAns));
}
.
.
.
}
Hopefuilly this helps ....
Mike
mdsgt@yahoo.com