gpt4 book ai didi

c# - 尝试将字符串的第一个符号转换为 int,得到奇怪的值

转载 作者:行者123 更新时间:2023-11-30 18:52:46 25 4
gpt4 key购买 nike

static void Main(string[] args)
{
string str_val = "8584348,894";
//int prefix = Convert.ToInt32(str_val[0]); //prefix = 56 O_o
//int prefix = (int)str_val[0]; //what, again 56? i need 8!
int prefix = Convert.ToInt32("8"); //at least this works -_-
}

知道如何将第一个符号转换为正确的数值吗?

最佳答案

如果您使用:

Convert.ToInt32(str_val[0]);

那么你实际上是在调用重载:

Convert.ToInt32(char val);

它给出了作为参数传递的字符的 Unicode/Ascii 编号。

如果要转换第一个字符,需要强制为字符串类型:

Convert.ToInt32(str_val.Substring(0, 1));

这样调用重载:

Convert.ToInt32(string val);

它实际上做你想做的(将字符串值转换为该字符串代表的 int 值)。

关于c# - 尝试将字符串的第一个符号转换为 int,得到奇怪的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11670105/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com