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

C#作业求助:如何将首字母大写的最长单词移至行首?

C#作业问题:移动首字母大写最长单词至行首并生成分析文件

作业任务

  • 读取文本文件L4_16T.txt,处理每行带指定分隔符的文本
  • 将每行中首字母大写的最长单词移至行首(保留原分隔符),修改后内容写入Results.txt
  • 生成表格格式的Analysis.txt,包含行号和该行所有首字母大写的单词

示例:

原字符串:Lorem Ipsum including versions of PageMaker
修改后:PageMaker Lorem Ipsum including versions of

当前问题

已能提取目标最长单词,但不知如何将其移至行首,允许使用正则表达式。现有代码如下:

using System;
using System.IO;
using System.Text;

namespace Lab_4
{
    internal class Program
    {
        const string strFile = "Text.txt";
        const string resFile = "Results.txt";
        const string aFile = "Analyz.txt";
        static void Main(string[] args)
        {   
            Process();
        }

        static void Process()
        {
            using (StreamReader reader = new StreamReader(strFile, Encoding.GetEncoding(1257)))
            {
                using (StreamWriter writer = new StreamWriter(resFile, true))
                {
                    string line;
                    char[] delimitars = { ' ', '.', ',', '!', '?', ':', ';', '(', ')', '\t' };
                    
                @k1:
                    while ((line = reader.ReadLine()) != null)
                    {
                        if (line == ""){ goto @k1;}
                        string LongestWord = TheLongestWord(line, delimitars);
                        writer.WriteLine(LongestWord);
                        Console.WriteLine(LongestWord);
                    }
                }
            }
        }

        static string TheLongestWord(string line, char[] delimitars)
        {

            string[] words = line.Split(delimitars);
            string longest = "";
            int length = 0, k = 0;

            try
            {
                for (int i = 0; i < words.Length; i++) {
                    for (int j = 0; j < words[k].Length; j++)
                    {
                        if (words[k].Length >= length)
                        {
                            if (Char.IsUpper(words[k][0]))
                            {
                                longest = words[k];
                                length = words[k].Length;
                            }
                        }
                    }
                    k++;
                }
            } catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            return longest;
        }
    }
}

解决方案

核心思路

  1. 修复最长单词提取逻辑,同时收集所有首字母大写单词用于分析文件
  2. 使用正则表达式匹配单词+后续分隔符,避免分割丢失原格式
  3. 将目标单词移至行首后拼接剩余内容

完整修改代码

using System;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Linq;

namespace Lab_4
{
    internal class Program
    {
        const string strFile = "L4_16T.txt"; // 修正文件名匹配作业要求
        const string resFile = "Results.txt";
        const string aFile = "Analysis.txt"; // 修正文件名拼写
        static void Main(string[] args)
        {   
            Process();
        }

        static void Process()
        {
            // 覆盖写入文件,避免重复追加内容
            using (StreamReader reader = new StreamReader(strFile, Encoding.GetEncoding(1257)))
            using (StreamWriter resultWriter = new StreamWriter(resFile, false, Encoding.GetEncoding(1257)))
            using (StreamWriter analysisWriter = new StreamWriter(aFile, false, Encoding.GetEncoding(1257)))
            {
                string line;
                int lineNumber = 0;
                // 匹配首字母大写的单词(支持含数字)
                Regex capitalizedWordRegex = new Regex(@"[A-Z][a-zA-Z0-9]*");
                // 匹配单词+后续所有分隔符,保留原格式
                Regex wordWithDelimiterRegex = new Regex(@"([A-Z][a-zA-Z0-9]*)([\s.,!?();:\t]*)");

                while ((line = reader.ReadLine()) != null)
                {
                    lineNumber++;
                    if (string.IsNullOrWhiteSpace(line))
                    {
                        resultWriter.WriteLine(line);
                        continue;
                    }

                    // 获取当前行所有首字母大写的单词
                    var capitalizedWords = capitalizedWordRegex.Matches(line)
                                                               .Cast<Match>()
                                                               .Select(m => m.Value)
                                                               .ToList();

                    // 生成分析文件的表格内容
                    if (lineNumber == 1)
                    {
                        analysisWriter.WriteLine("| 行号 | 首字母大写单词 |");
                        analysisWriter.WriteLine("|---|---|");
                    }
                    analysisWriter.WriteLine($"| {lineNumber} | {string.Join(", ", capitalizedWords)} |");

                    if (!capitalizedWords.Any())
                    {
                        resultWriter.WriteLine(line);
                        continue;
                    }

                    // 找到最长的首字母大写单词(长度相同取第一个)
                    string longestWord = capitalizedWords.OrderByDescending(w => w.Length).First();

                    // 标记要移动的单词及其分隔符,再拼接至行首
                    string modifiedLine = wordWithDelimiterRegex.Replace(line, match => 
                    {
                        return match.Groups[1].Value == longestWord ? $"__MOVE__{match.Value}" : match.Value;
                    });
                    string toMove = modifiedLine.Substring(modifiedLine.IndexOf("__MOVE__") + 7);
                    modifiedLine = modifiedLine.Replace($"__MOVE__{toMove}", "").TrimStart();
                    modifiedLine = $"{toMove}{modifiedLine}";

                    resultWriter.WriteLine(modifiedLine);
                }
            }
        }
    }
}

关键说明

  • 正则匹配:([A-Z][a-zA-Z0-9]*)([\s.,!?();:\t]*)确保移动单词时保留原分隔符格式
  • 分析文件:采用Markdown表格格式,清晰展示行号与对应大写单词
  • 空行处理:保留原文件空行,避免破坏文本结构
  • 编码统一:读写均使用Encoding.GetEncoding(1257),防止乱码

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 23:10:12