【问题标题】:C#: Char to string [duplicate]C#:字符到字符串 [重复]
【发布时间】:2018-10-01 21:03:28
【问题描述】:

为什么当我在每一行输入一个输入=“a”“b”“c”时,我得到的不是输出“abc”而是“294”?我知道他们从 ascii 表中获取每个字母的编号,但是有人可以解释我该怎么做才能获得“abc”吗?

using System;

namespace CharsToString
{
    public class Program
    {
        public static void Main()
        {
            char firstInput = char.Parse(Console.ReadLine());
            char secondInput = char.Parse(Console.ReadLine());
            char thirdInput = char.Parse(Console.ReadLine());

            Console.WriteLine(firstInput + secondInput + thirdInput);
        }
    }
}

【问题讨论】:

  • A char 是一个整数类型,所以你不能连接它,你只是添加值。可以使用StringBuilder构造字符串
  • 使用StringBuilder将字符累加成字符串
  • @pm 除非您转换为字符串或分三步完成,否则这将不起作用。
  • 如果你只想抓住用户按下的第一个键,你可能想看看Console.ReadKey()方法。

标签: c#


【解决方案1】:

char 是一个整数类型,您要添加需要在每个上调用 ToString 的值

Console.WriteLine(firstInput.ToString() + secondInput.ToString() + thirdInput.ToString());

您也可以使用字符串生成器,但鉴于示例,这似乎是过早的优化

【讨论】:

  • 最后两个 .ToString() 可以是隐式的(因为存在重载 operator +(string, object)),所以:Console.WriteLine(firstInput.ToString() + secondInput + thirdInput); 另一种选择是:Console.WriteLine($"{firstInput}{secondInput}{thirdInput}");
  • @JeppeStigNielsen,我认为最好明确一点,不要混淆操作,但你有一个很好的观点,这可以简化
  • 有些人甚至会这样做Console.WriteLine("" + firstInput + secondInput + thirdInput);
猜你喜欢
  • 2016-03-09
  • 2013-09-14
  • 1970-01-01
  • 1970-01-01
  • 2020-04-20
  • 2023-03-09
  • 2013-08-20
  • 2013-08-04
  • 1970-01-01
相关资源
最近更新 更多