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

如何在C#中移除字符串中由n个字母组成的单词?

问题修正方案

你的代码存在几个关键问题:

  1. Func方法的参数类型错误:接收的n应该是整数类型(用户输入的是单词长度),但你定义成了string类型,导致调用时类型不匹配。
  2. 核心逻辑错误:text.Replace(text, n)完全不符合需求,这是把整个文本替换成n的字符串形式,而不是过滤指定长度的单词。
  3. 未处理分割后可能出现的空字符串(比如连续空格的情况)。

以下是修正后的完整代码:

using System;
using System.Collections.Generic;

namespace project
{
    class Program
    {
        public static string RemoveWordsByLength(string text, int targetLength)
        {
            // 按空格分割,同时移除连续空格产生的空字符串
            string[] words = text.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            List<string> filteredWords = new List<string>();
            
            // 筛选出长度不等于目标值的单词
            foreach (string word in words)
            {
                if (word.Length != targetLength)
                {
                    filteredWords.Add(word);
                }
            }
            
            // 将筛选后的单词重新拼接成字符串
            return string.Join(" ", filteredWords);
        }

        static void Main(string[] args)
        {
            Console.WriteLine("Enter the number of letters in the word: ");
            // 增加输入验证,避免非整数输入导致程序崩溃
            if (!int.TryParse(Console.ReadLine(), out int n))
            {
                Console.WriteLine("Invalid input, please enter an integer.");
                return;
            }

            Console.WriteLine("\nEnter the string: ");
            string text = Console.ReadLine();
            
            Console.WriteLine($"A string that does not contain a word with {n} letters:");
            Console.WriteLine(RemoveWordsByLength(text, n));
        }
    }
}

关键修正说明:

  • 重命名方法为RemoveWordsByLength,让语义更清晰,参数改为int targetLength匹配需求。
  • 使用StringSplitOptions.RemoveEmptyEntries处理连续空格导致的空单词问题。
  • 遍历单词数组,筛选出长度不符合目标值的单词,再用string.Join拼接成结果字符串。
  • 增加int.TryParse做输入验证,防止用户输入非整数导致程序报错。

内容的提问来源于stack exchange,提问作者Min-Max_Reid

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 01:01:07