在没有库函数的情况下将字符串转换为C#中的整数

编程入门 行业动态 更新时间:2024-10-28 04:25:12
本文介绍了在没有库函数的情况下将字符串转换为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#中的整数

本文发布于:2023-10-25 22:33:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1528309.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:整数   字符串   转换为   情况下   库函数

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!