You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何C#程序控制台输出数字而非预期的字母?

提取字符串中间字符时输出整数而非字母的问题

问题描述

程序原本要提取单词的两个中间字符(以"Test"为例,期望得到"es"),但运行后返回的是整数而非字母。

原代码

using System;
using System.Linq;

class Program
{
    public static void Main(string[] args)
    {
        string word = "Test";

        int wordLength = word.Count();

        if (wordLength % 2 == 0)
        {
            int middle = word[wordLength / 2];
            int nextAlong = middle + 1;
            Console.WriteLine("Even number");
            Console.WriteLine("{0},{1}", middle, nextAlong);
        }
        else
        {
            Console.WriteLine("Odd number");
            Console.WriteLine(word[wordLength / 2]);    
        }
    }
}

控制台输出

Even number
115,116

问题原因

  1. 类型转换问题:C#中char类型本质是UTF-16代码单元,当把word[index]赋值给int变量时,会自动转换为对应的ASCII/Unicode数值,所以输出数字而非字符。
  2. 索引逻辑错误:nextAlong = middle + 1是将字符的数值加1,而非取下一个位置的字符;同时原代码只取了第二个中间字符的索引,漏掉了前一个中间字符的位置。

修正后的代码

using System;
using System.Linq;

class Program
{
    public static void Main(string[] args)
    {
        string word = "Test";

        int wordLength = word.Count();

        if (wordLength % 2 == 0)
        {
            // 偶数长度时,中间两个字符的索引为 length/2 -1 和 length/2
            char middleLeft = word[wordLength / 2 - 1];
            char middleRight = word[wordLength / 2];
            Console.WriteLine("Even number");
            Console.WriteLine("{0},{1}", middleLeft, middleRight);
        }
        else
        {
            Console.WriteLine("Odd number");
            // 直接输出char类型,显示字符而非数值
            Console.WriteLine(word[wordLength / 2]);    
        }
    }
}

修正说明

  • 将变量类型从int改为char,确保输出时显示字符本身而非对应的数值。
  • 调整索引逻辑:对于偶数长度的字符串,两个中间字符的正确位置是wordLength/2 -1和wordLength/2(比如"Test"长度为4,对应索引1的'e'和索引2的's')。
  • 移除错误的数值累加逻辑,直接通过索引获取目标字符。

内容的提问来源于stack exchange,提问作者user19678715

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 22:09:37