不使用C#中的类型转换将字符串更改为整数 [英] change string to integer without using typecasting in C#
本文介绍了不使用C#中的类型转换将字符串更改为整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
将129之类的字符串更改为整数类型129而不使用类型转换为convert.toint32(字符串)....
谢谢
解决方案
< blockquote>
int x = 0 ;
Int32 .TryParse( 100, out x);
将字符串解析为字符,将每个char int值乘以10 ^(反向索引的char);
使用系统;
使用 System.Linq;
命名空间 ParseTest
{
public class 程序
{
静态 void Main()
{
var s = 129\" 跨度>;
var r = s.Reverse();
var sum = 0 ;
for ( var i = 0 ; i < r.Count(); ++ i)
{
sum + =(r.ElementAt(i) - ' 0')*( int ) Math.Pow( 10 ,i);
}
Console.WriteLine( int is {0},sum);
}
}
}
此外,我认为我不需要指出如果这是一个真正的应用程序你不应该这样做,而是使用内置的转换。
但是,作为纯粹的学术练习,上述内容应该有效。
希望这会有所帮助,
Fredrik
我不确定 Google [ ^ ]被打破了你的地方?或者他们阻止了MSDN?
查看MSDN文档来执行此操作。
http://msdn.microsoft.com/en-us/library/vstudio/bb397679.aspx [ ^ ]
我建议查看Int32 .TryParse(字符串, out int )。
change string like 129 into integer type 129 without using typecasting as convert.toint32(string)....
thank you
解决方案
int x = 0; Int32.TryParse("100", out x);
Parse the string into chars, multiply each char int value by 10^(reversed index of char);
using System; using System.Linq; namespace ParseTest { public class Program { static void Main() { var s = "129"; var r = s.Reverse(); var sum = 0; for (var i = 0; i < r.Count(); ++i) { sum += (r.ElementAt(i) - '0') * (int)Math.Pow(10, i); } Console.WriteLine("int is {0}", sum); } } }
Also, I don't think I need to point out that you shouldn't be doing this if this is for a real application, use the built in conversions instead.
But, for as a purely academic exercise, the above should work.
Hope this helps,
Fredrik
I am not sure if Google [^]is broken at your place? Or they blocked MSDN?
Look at the MSDN documentation to do this.
http://msdn.microsoft.com/en-us/library/vstudio/bb397679.aspx[^]
I would recommend to look intoInt32.TryParse(string, out int)as well.
这篇关于不使用C#中的类型转换将字符串更改为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文