C#字符串指定字符索引定位与替换问题求助(禁用LINQ)
字符替换程序的问题分析与修复方案
嗨,我来帮你解决这个问题~你遇到的重复索引问题,根源在于IndexOf的调用方式不对,咱们一步步来拆解:
你的代码问题所在
你现在的循环里,每次都执行findIndex[i] = myString.IndexOf(myCharacter, 0)——这个方法每次都会从字符串的起始位置(0)开始查找第一个匹配的字符,所以不管循环多少次,得到的都是同一个索引值(比如示例里的2),自然数组里全是重复的数字了。而且如果没有匹配到,还会存入-1,这也不是你想要的结果。
另外,用固定长度的int[]来存索引也不太合理,因为匹配的字符数量可能远小于字符串长度,会浪费空间。
两种可行的修复方案(均不使用LINQ)
方案1:直接遍历字符数组替换(最直观高效)
因为C#的字符串是不可变的,所以我们可以先把字符串转换成char[],然后逐个检查字符,找到目标字符就替换,最后再转回字符串。
public static void ReplaceSpecifiedCharacters() { Console.WriteLine("\nWrite a word/sentence: "); string myString = Console.ReadLine(); if (string.IsNullOrEmpty(myString)) { Console.WriteLine("输入不能为空哦!"); return; } Console.Write("Type the character you would like to replace: "); string inputChar = Console.ReadLine(); // 确保用户输入的是单个字符 if (string.IsNullOrEmpty(inputChar) || inputChar.Length != 1) { Console.WriteLine("请输入单个字符!"); return; } char targetChar = inputChar[0]; Console.Write("Type the character to replace with: "); string replaceWithInput = Console.ReadLine(); if (string.IsNullOrEmpty(replaceWithInput) || replaceWithInput.Length != 1) { Console.WriteLine("请输入单个替换字符!"); return; } char replaceChar = replaceWithInput[0]; // 转成char数组方便修改 char[] charArray = myString.ToCharArray(); for (int i = 0; i < charArray.Length; i++) { if (charArray[i] == targetChar) { charArray[i] = replaceChar; } } // 转回字符串并输出结果 string result = new string(charArray); Console.WriteLine($"替换后的结果:{result}"); }
方案2:先收集所有匹配的索引,再替换
如果你坚持要先收集索引再替换,可以用List<int>来动态存储找到的索引(避免固定数组的浪费),并且每次找到索引后,从下一个位置继续查找,直到找不到为止:
public static void ReplaceSpecifiedCharactersWithIndexCollection() { Console.WriteLine("\nWrite a word/sentence: "); string myString = Console.ReadLine(); if (string.IsNullOrEmpty(myString)) { Console.WriteLine("输入不能为空哦!"); return; } Console.Write("Type the character you would like to replace: "); string inputChar = Console.ReadLine(); if (string.IsNullOrEmpty(inputChar) || inputChar.Length != 1) { Console.WriteLine("请输入单个字符!"); return; } char targetChar = inputChar[0]; Console.Write("Type the character to replace with: "); string replaceWithInput = Console.ReadLine(); if (string.IsNullOrEmpty(replaceWithInput) || replaceWithInput.Length != 1) { Console.WriteLine("请输入单个替换字符!"); return; } char replaceChar = replaceWithInput[0]; // 收集所有匹配的索引 List<int> findIndex = new List<int>(); int currentIndex = myString.IndexOf(targetChar); while (currentIndex != -1) { findIndex.Add(currentIndex); // 从下一个位置继续查找 currentIndex = myString.IndexOf(targetChar, currentIndex + 1); } // 转成char数组进行替换 char[] charArray = myString.ToCharArray(); foreach (int index in findIndex) { charArray[index] = replaceChar; } string result = new string(charArray); Console.WriteLine($"替换后的结果:{result}"); // 也可以输出收集到的索引 Console.WriteLine("找到的索引位置:" + string.Join(", ", findIndex)); }
测试示例
比如输入Hello,要替换的字符是l,替换成$:
- 方案1和方案2都会输出
He$$o,方案2还会输出找到的索引位置:2, 3,完全符合你的需求。
内容的提问来源于stack exchange,提问作者Amit
相关产品推荐
相关产品推荐

