简体   繁体   English

为什么字符串添加结果如此奇怪?

[英]Why does string addition result is so weird?

public static void Main(string[] args)
{
     int num = 1;
     string number = num.ToString();
     Console.WriteLine(number[0]);
     Console.WriteLine(number[0] + number[0]);
}

I expect the output of 1 and 11 but I'm getting 1 and 98 . 我期望111的输出,但我得到198 What am I missing? 我错过了什么?

The type of number[0] is char , not string - you're not performing any string concatenation. number[0]的类型是char ,而不是string - 您没有执行任何字符串连接。 Instead, you've got a char with value 49 (the UTF-16 value for '1'). 相反,你有一个值为49的char ('1'的UTF-16值)。 There's no +(char, char) operator, so both operands are being promoted to int and you're performing integer addition. 没有+(char, char)运算符,因此两个操作数都被提升为int并且您正在执行整数加法。

So this line: 所以这一行:

Console.WriteLine(number[0] + number[0]);

is effectively this: 实际上是这样的:

char op1 = number[0];
int promoted1 = op1;

char op2 = number[0];
int promoted2 = op2;

int sum = promoted1 + promoted2;
Console.WriteLine(sum);

(It's possible that logically the promotion happens after both operands have been evaluated - I haven't checked the spec, and as it won't fail, it doesn't really matter.) (逻辑上,在两个操作数被评估之后,促销发生了 - 我没有检查规范,因为它不会失败,所以它并不重要。)

Because of [], this give the first char of the string. 由于[],这给出了字符串的第一个字符。

number[0] + number[0] is doing 49 + 49 (the ascii code of char 1); number[0] + number[0]正在执行49 + 49(char 1的ascii代码);

I think you want to do this : 我想你想这样做:

public static void Main(string[] args)
{
    int num = 1;
    string number = num.ToString();
    Console.WriteLine(number);
    Console.WriteLine(number + number);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM