C#字符串单词反转功能异常求助:程序中途停止反转
问题分析与修复
你的代码出现反转到中途停止的问题,核心原因是数组引用赋值导致的错误:
string[] subsc = subs;
这行代码并没有创建新数组,只是让subsc和subs指向同一个内存地址的数组。当你在第二个循环中修改subs[i]时,subsc的内容会同步改变——因为它们本质是同一个数组。循环执行到后半段时,你读取的subsc元素已经是被修改过的值,而非原始数组的内容,最终导致反转失败。
修复方案
方案1:创建原始数组的独立副本
通过复制数组,让subsc保存原始数据,修改subs时不会影响它:
void ReverseString(string input) { string[] subs = input.Split(' '); // 创建数组副本,而非引用赋值 string[] subsc = subs.ToArray(); // 输出原句 for (int i = 0; i < subs.Length; i++) { Console.Write(subs[i] + " "); } // 使用副本的原始数据反转 for (int i = 0; i < subsc.Length; i++) { subs[i] = subsc[subsc.Length - 1 - i]; } Console.WriteLine(); // 输出反转后的句子 for (int i = 0; i < subs.Length; i++) { Console.Write(subs[i] + " "); } }
方案2:原地交换元素(更高效)
不需要额外数组,直接在原数组上交换首尾对应的元素,循环只需要执行到数组长度的一半:
void ReverseString(string input) { string[] subs = input.Split(' '); // 输出原句 for (int i = 0; i < subs.Length; i++) { Console.Write(subs[i] + " "); } // 原地交换元素实现反转 for (int i = 0; i < subs.Length / 2; i++) { int oppositeIndex = subs.Length - 1 - i; string temp = subs[i]; subs[i] = subs[oppositeIndex]; subs[oppositeIndex] = temp; } Console.WriteLine(); // 输出反转后的句子 for (int i = 0; i < subs.Length; i++) { Console.Write(subs[i] + " "); } }
正确运行结果
调用ReverseString("Write a C# program to display the following pattern using the alphabet.");后,输出为:
Write a C# program to display the following pattern using the alphabet. alphabet. the using pattern following the display to program C# a Write
内容的提问来源于stack exchange,提问作者Physalis
相关产品推荐
相关产品推荐

