C#字符串字符按位置格式化问题及代码报错求助
字符串格式化功能实现及问题修复
需求说明
实现字符串格式化:将字符串中每个字符按其在单词中的序号(从0开始)重复对应次数,首字母大写、其余小写,各部分用连字符分隔。示例:
- "abcd" → "A-Bb-Ccc-Dddd"
- "RqaEzty" → "R-Qq-Aaa-Eeee-Zzzzz-Tttttt-Yyyyyyy"
- "cwAt" → "C-Ww-Aaa-Tttt"
错误代码
public static String Accum(string s) { string res; for(int i = 0; i < s.Length; i++) { res += s[i].ToUpper() + s[i].ToLower().Repeat(i) + (i < s.Length - 1 ? "-":"")); } return res; }
报错信息
- error CS1501: No overload for method 'ToUpper' takes 0 arguments
- error CS0165: Use of unassigned local variable 'res'
错误修复及完整代码
1. 未初始化局部变量res
C#要求局部变量必须显式初始化才能使用。原代码中string res;仅声明变量但未赋值,执行res +=时会触发CS0165错误。只需将变量初始化为空字符串:
string res = string.Empty;
2. 字符大小写转换调用错误
s[i]是char类型,ToUpper/ToLower是char类的静态方法,不能直接通过实例调用,正确写法是char.ToUpper(s[i])和char.ToLower(s[i])。此外,C#的string没有内置Repeat方法,可通过new string(char, int)构造函数生成重复的字符序列。
修正后的完整代码
public static string Accum(string s) { string res = string.Empty; for (int i = 0; i < s.Length; i++) { char current = s[i]; // 拼接首字母大写 + i次小写字符 string segment = char.ToUpper(current).ToString() + new string(char.ToLower(current), i); // 添加连字符(最后一个元素不加) res += segment + (i < s.Length - 1 ? "-" : ""); } return res; }
简化写法(使用LINQ)
如果项目引用了System.Linq,可以用更简洁的方式实现:
using System.Linq; public static string Accum(string s) { return string.Join("-", s.Select((c, idx) => char.ToUpper(c) + new string(char.ToLower(c), idx))); }
内容的提问来源于stack exchange,提问作者Vaynore
相关产品推荐
相关产品推荐

