C#中统计连续字符出现次数,如何实现可修改的有序<char,int>集合?
可行解决方案
针对连续字符统计且需维护顺序、支持修改的需求,推荐以下几种实用方案:
1. 自定义实体类 + List
这是最直观灵活的方案,自定义一个包含字符和计数属性的类,用List<T>存储,既保证顺序,又能随时修改属性值。
代码示例(C#):
// 自定义类 public class CharCount { public char Character { get; set; } public int Count { get; set; } } // 连续字符统计逻辑 string input = "aabaccbb"; List<CharCount> result = new List<CharCount>(); if (string.IsNullOrEmpty(input)) return result; char currentChar = input[0]; int currentCount = 1; for (int i = 1; i < input.Length; i++) { if (input[i] == currentChar) { currentCount++; } else { result.Add(new CharCount { Character = currentChar, Count = currentCount }); currentChar = input[i]; currentCount = 1; } } // 添加最后一组字符 result.Add(new CharCount { Character = currentChar, Count = currentCount }); // 修改示例:将第一个元素的计数加1 result[0].Count += 1;
2. 可变值元组 + List
如果不想额外定义类,可以用C#的命名值元组,它的元素支持修改,同样用List<T>维护顺序。
代码示例(C#):
string input = "aabaccbb"; List<(char Char, int Count)> result = new List<(char Char, int Count)>(); if (string.IsNullOrEmpty(input)) return result; var current = (Char: input[0], Count: 1); for (int i = 1; i < input.Length; i++) { if (input[i] == current.Char) { current.Count++; } else { result.Add(current); current = (input[i], 1); } } result.Add(current); // 修改示例:调整第二个元素的计数 var item = result[1]; item.Count = 2; result[1] = item;
3. 自定义集合(进阶)
如果需要更封装的操作,可以自定义一个继承自Collection<KeyValuePair<char, int>>的集合类,重写相关方法支持修改键值对内容,适合有特定扩展需求的场景。
简化示例:
public class MutableCharCountCollection : Collection<KeyValuePair<char, int>> { // 提供修改指定位置元素的方法 public void Update(int index, char newChar, int newCount) { if (index < 0 || index >= Count) throw new ArgumentOutOfRangeException(nameof(index)); SetItem(index, new KeyValuePair<char, int>(newChar, newCount)); } } // 使用方式 var collection = new MutableCharCountCollection(); // 统计逻辑类似,添加元素时调用collection.Add(new KeyValuePair<char, int>(currentChar, currentCount)) // 修改时调用collection.Update(0, 'a', 3);
内容的提问来源于stack exchange,提问作者Ali_Hmt10
相关产品推荐
相关产品推荐

