簡體   English   中英

在 Java 中手動將字符串轉換為整數

[英]Manually converting a string to an integer in Java

我有一個由一系列數字組成的字符串(例如"1234" )。 如何在不使用Integer.parseInt等 Java 庫函數的情況下將String作為int返回?

public class StringToInteger {
  public static void main(String [] args){
    int i = myStringToInteger("123");
    System.out.println("String decoded to number " + i);
  }

  public int myStringToInteger(String str){
      /* ... */
  }
}

這有什么問題?

int i = Integer.parseInt(str);

編輯 :

如果您確實需要手動進行轉換,請嘗試以下操作:

public static int myStringToInteger(String str) {
    int answer = 0, factor = 1;
    for (int i = str.length()-1; i >= 0; i--) {
        answer += (str.charAt(i) - '0') * factor;
        factor *= 10;
    }
    return answer;
}

以上對於正整數來說可以正常工作,如果數字是負數,你必須先做一些檢查,但我會把它作為練習留給讀者。

如果不允許使用標准庫,有很多方法可以解決這個問題。 考慮這一點的一種方法是作為遞歸函數:

  1. 如果 n 小於 10,只需將其轉換為包含其數字的單字符字符串。 例如,3 變為“3”。
  2. 如果 n 大於 10,則用除法和取模得到 n 的最后一位以及排除最后一位形成的數字。 遞歸獲取第一個數字的字符串,然后為最后一個數字附加適當的字符。 例如,如果 n 為 137,您將遞歸計算“13”並添加“7”以獲得“137”。

您將需要邏輯來處理特殊情況 0 和負數,否則這可以相當簡單地完成。

由於我懷疑這可能是家庭作業(並且知道在某些學校確實如此),因此我將把實際的轉換作為練習留給讀者。 :-)

希望這可以幫助!

在這種情況下使用 long 而不是 int。 您需要檢查溢出。

public static int StringtoNumber(String s) throws Exception{
    if (s == null || s.length() == 0)
        return 0;
    while(s.charAt(0) == ' '){
        s = s.substring(1);
    }
    boolean isNegative = s.charAt(0) == '-';
    if (s.charAt(0) == '-' || (s.charAt(0) == '+')){
        s = s.substring(1);
    }

    long result = 0l;
    for (int i = 0; i < s.length(); i++){
        int value = s.charAt(i) - '0';
        if (value >= 0 && value <= 9){
            if (!isNegative && 10 * result + value > Integer.MAX_VALUE ){
                throw new Exception();
            }else if (isNegative && -1 * 10 * result - value < Integer.MIN_VALUE){
                throw new Exception();
            }
            result = 10 * result + value;
        }else if (s.charAt(i) != ' '){
            return (int)result;
        }
    }
    return isNegative ? -1 * (int)result : (int)result;
}

已在此處發布的答案的替代方法。 您可以從前面遍歷字符串並構建數字

 public static void stringtoint(String s){      
    boolean isNegative=false;
    int number =0;      
    if (s.charAt(0)=='-') {
        isNegative=true;            
    }else{
        number = number* 10 + s.charAt(0)-'0';
    }

    for (int i = 1; i < s.length(); i++) {

        number = number*10 + s.charAt(i)-'0';           
    }
    if(isNegative){
        number = 0-number;
    }
    System.out.println(number);
}

如果有正確的提示,我認為大多數受過高中教育的人都可以自己解決這個問題。 每個人都知道134 = 100x1 + 10x3 + 1x4

大多數人錯過的關鍵部分是,如果你在 Java 中做這樣的事情

 System.out.println('0'*1);//48

它將在ascii 圖表中選擇字符0 的十進制表示並將其乘以 1。

ascii 表中,字符 0 的十進制表示為 48。所以上面的行將打印 48。所以如果你執行類似 '1'-'0' 之類的操作,則與 49-48 相同。 由於在 ascii 圖表中,字符 0-9 是連續的,因此您可以將 0 到 9 之間的任何字符減去 0 以獲得其整數值。 一旦你有了一個字符的整數值,那么將整個字符串轉換為 int 就很簡單了。

這是該問題的另一種解決方案

String a = "-12512";
char[] chars = a.toCharArray();
boolean isNegative = (chars[0] == '-');
if (isNegative) {
    chars[0] = '0';
}

int multiplier = 1;
int total = 0;

for (int i = chars.length - 1; i >= 0; i--) {
    total = total + ((chars[i] - '0') * multiplier);
    multiplier = multiplier * 10;
}

if (isNegative) {
    total = total * -1;
}

使用 Java 8,您可以執行以下操作:

public static int convert(String strNum)
{
   int result =strNum.chars().reduce(0, (a, b)->10*a +b-'0');
}
  1. 將 srtNum 轉換為 char
  2. 對於每個字符(表示為 'b')-> 'b' -'0' 將給出相對數
  3. sum all in a (initial value is 0) (每次我們對 char 執行操作時 -> a=a*10

用這個:

static int parseInt(String str) {
    char[] ch = str.trim().toCharArray();
    int len = ch.length;
    int value = 0;
    for (int i=0, j=(len-1); i<len; i++,j--) {
        int c = ch[i];
        if (c < 48 || c > 57) {
            throw new NumberFormatException("Not a number: "+str);
        }
        int n = c - 48;
        n *= Math.pow(10, j);
        value += n;
    }
    return value;
}

順便說一句,你可以處理負整數的特殊情況,否則會拋出異常NumberFormatException

您可以這樣做:從字符串中,為每個元素創建一個字符數組,保存索引,並將其 ASCII 值乘以實際反向索引的冪。 將部分因素相加,你就得到了。

使用Math.pow只需進行少量轉換(​​因為它返回一個雙Math.pow值),但您可以通過創建自己的冪函數來避免這種情況。

public static int StringToInt(String str){
    int res = 0;
    char [] chars = str.toCharArray();
    System.out.println(str.length());
    for (int i = str.length()-1, j=0; i>=0; i--, j++){
        int temp = chars[j]-48;
        int power = (int) Math.pow(10, i);
        res += temp*power;
        System.out.println(res);
    }
    return res;
}
public int myStringToInteger(String str) throws NumberFormatException 
{
    int decimalRadix = 10; //10 is the radix of the decimal system

    if (str == null) {
        throw new NumberFormatException("null");
    }

    int finalResult = 0;
    boolean isNegative = false;
    int index = 0, strLength = str.length();

    if (strLength > 0) {
        if (str.charAt(0) == '-') {
            isNegative = true;
            index++;
        } 

        while (index < strLength) {

            if((Character.digit(str.charAt(index), decimalRadix)) != -1){   
                finalResult *= decimalRadix;
                finalResult += (str.charAt(index) - '0');
            } else throw new NumberFormatException("for input string " + str);

            index++;
        }

    } else {
        throw new NumberFormatException("Empty numeric string");
    }

    if(isNegative){
        if(index > 1)
            return -finalResult;
        else
            throw new NumberFormatException("Only got -");
    }

    return finalResult;
}

結果:1)對於輸入“34567”,最終結果將是:34567 2)對於輸入“-4567”,最終結果將是:-4567 3)對於輸入“-”,最終結果將是:java。 lang.NumberFormatException: Only got - 4) 對於輸入“12ab45”,最終結果將是:java.lang.NumberFormatException: for input string 12ab45

public static int convertToInt(String input){
        char[] ch=input.toCharArray();
        int result=0;
        for(char c : ch){
            result=(result*10)+((int)c-(int)'0');
        }
        return result;
    }

也許這種方式會快一點:

public static int convertStringToInt(String num) {
     int result = 0;

     for (char c: num.toCharArray()) {
        c -= 48;
        if (c <= 9) {
            result = (result << 3) + (result << 1) + c;
        } else return -1;
    }
    return result;
}

這是一個完整的程序,所有條件都是正面的,負面的,不使用庫

import java.util.Scanner;
public class StringToInt {
 public static void main(String args[]) {
  String inputString;
  Scanner s = new Scanner(System.in);
  inputString = s.nextLine();

  if (!inputString.matches("([+-]?([0-9]*[.])?[0-9]+)")) {
   System.out.println("error!!!");
  } else {
   Double result2 = getNumber(inputString);
   System.out.println("result = " + result2);
  }

 }
 public static Double getNumber(String number) {
  Double result = 0.0;
  Double beforeDecimal = 0.0;
  Double afterDecimal = 0.0;
  Double afterDecimalCount = 0.0;
  int signBit = 1;
  boolean flag = false;

  int count = number.length();
  if (number.charAt(0) == '-') {
   signBit = -1;
   flag = true;
  } else if (number.charAt(0) == '+') {
   flag = true;
  }
  for (int i = 0; i < count; i++) {
   if (flag && i == 0) {
    continue;

   }
   if (afterDecimalCount == 0.0) {
    if (number.charAt(i) - '.' == 0) {
     afterDecimalCount++;
    } else {
     beforeDecimal = beforeDecimal * 10 + (number.charAt(i) - '0');
    }

   } else {
    afterDecimal = afterDecimal * 10 + number.charAt(i) - ('0');
    afterDecimalCount = afterDecimalCount * 10;
   }
  }
  if (afterDecimalCount != 0.0) {
   afterDecimal = afterDecimal / afterDecimalCount;
   result = beforeDecimal + afterDecimal;
  } else {
   result = beforeDecimal;
  }

  return result * signBit;
 }
}
Works for Positive and Negative String Using TDD

//Solution

public int convert(String string) {
    int number = 0;
    boolean isNegative = false;
    int i = 0;
    if (string.charAt(0) == '-') {
        isNegative = true;
        i++;
    }

    for (int j = i; j < string.length(); j++) {
        int value = string.charAt(j) - '0';
        number *= 10;
        number += value;
    }
    if (isNegative) {
        number = -number;
    }

    return number;
}

//測試用例

public class StringtoIntTest {
private StringtoInt stringtoInt;


@Before
public void setUp() throws Exception {
stringtoInt = new StringtoInt();
}

@Test
public void testStringtoInt() {
    int excepted = stringtoInt.convert("123456");
    assertEquals(123456,excepted);
}

@Test
public void testStringtoIntWithNegative() {
    int excepted = stringtoInt.convert("-123456");
    assertEquals(-123456,excepted);
}

}

    //Take one positive or negative number
    String str="-90997865";

    //Conver String into Character Array
    char arr[]=str.toCharArray();

    int no=0,asci=0,res=0;

    for(int i=0;i<arr.length;i++)
    {
       //If First Character == negative then skip iteration and i++
       if(arr[i]=='-' && i==0)
       {
           i++;
       }

           asci=(int)arr[i]; //Find Ascii value of each Character 
           no=asci-48; //Now Substract the Ascii value of 0 i.e 48  from asci
           res=res*10+no; //Conversion for final number
    }

    //If first Character is negative then result also negative
    if(arr[0]=='-')
    {
        res=-res;
    }

    System.out.println(res);

利用 Java 以相同方式使用 char 和 int 的事實。 基本上,執行 char - '0' 來獲取 char 的 int 值。

public class StringToInteger {
    public static void main(String[] args) {
        int i = myStringToInteger("123");
        System.out.println("String decoded to number " + i);
    }

    public static int myStringToInteger(String str) {
        int sum = 0;
        char[] array = str.toCharArray();
        int j = 0;
        for(int i = str.length() - 1 ; i >= 0 ; i--){
            sum += Math.pow(10, j)*(array[i]-'0');
            j++;
        }
        return sum;
    }
}
public class ConvertInteger {

public static int convertToInt(String numString){
    int answer = 0, factor = 1;

    for (int i = numString.length()-1; i >= 0; i--) {
        answer += (numString.charAt(i) - '0') *factor;
        factor *=10;
    }
    return answer;
}

public static void main(String[] args) {

    System.out.println(convertToInt("789"));
}

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM