October 8, 2010
String to Long
Problem
Write a java program to convert a character string into long data type.
Solution
We have already solved this problem using C++ in the post String to Integer. The code below shows a java implementation.
Code
Here is the code in Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
//Main class public class String2Long { //Main function public static void main(String[] args) { //Test string to long function long i = StringToLong("123"); //Check if string is converted successfully if (i == 123) { System.out.println("Yes: i = 123"); } else { System.out.println("No: i != 123"); } } //Function to convert string to long static long StringToLong(String s) { //Return value long ret = 0; //This is needed to calculate powers of 10 int power = 1; //Loop in the string character by character //Get the current digit by subtracting the //ASCII code of '0' from its ASCII code. //You need to cast the rest to integer //type. Then multiply the result by 10 //raised to a power equal to the position //of the character from right to left starting //the count from 0 for (int i = s.length()-1; i >= 0; i--) { ret += ((int)s.charAt(i)-(int)'0') * power; power *= 10; } //Return final result return ret; } } |