在没有库函数的情况下将字符串转换为C#中的整数 [英] convert string to integer in C# without library functions

查看:105
本文介绍了在没有库函数的情况下将字符串转换为C#中的整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以举一个没有库函数的C#中将字符串转换为整数的示例吗?

can any one give an example for converting string to integer in C# without library functions

推荐答案

一个不太复杂的示例:

A somewhat less convoluted example:

int StrToInt(string str)
{
    int response = 0;
    foreach (char c in str)
    {
        response *= 10;
        response += c - ''0'';
    }
    return response;
}



显然,需要添加一些额外的代码来进行错误检查,签名等,但是我敢肯定您可以很容易地弄清楚这一点.



Obviously some extra code needs to be added for error checking, sign etc, but I''m sure you can figure that out quite easily.


但是为什么呢?由于已经加载了框架,为什么不使用功能而不是重新发明轮子呢?这个问题根本没有道理.
But why? Since the framework is already loaded, why not make use of the functionality instead of reinventing the wheel? This question makes no sense at all.


一种实现方法是通过代码.不漂亮,但是就在这里.
这只能用于基本上是整数的字符串输入(例如123,43785等),并且仅适用于正整数-但看到这一点,您将得到大致的了解:).

One way to do it is through code. Not pretty, but here it is.
This can only be used for string inputs that are basically integers (e.g.123,43785 etc) and works for only positive integers - but seeing this you''ll get the general idea :) .

public static void Main() {
    string str = Console.ReadLine();
    int j = 0;
    int myNumber = 0;
    string strReverse =String.Empty;

    //Reverse the string
    foreach (char temp in str)
    {
        strReverse = temp + strReverse;
    }

    foreach (char temp in strReverse)
    {
        int i = temp - 48; //Ascii character
        myNumber = myNumber + i * myPower(10,j);
        j++;
    }
    Console.WriteLine(myNumber);
    Console.ReadLine();
}


public static int myPower(int i, int j)
{
    int final = 1;
    for (int loop =0 ; loop < j; loop++)
        final = final  * i;
    return final;
}


这篇关于在没有库函数的情况下将字符串转换为C#中的整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆