给定一个只有_和大写字母组成的字符串,_用于分割单词。将它转换为一个新的字符串,新字符串前缀CddMotor,后缀Set,中间内容是原始字符串去掉_,且每个首字母大写,使用C#实现一个函数
时间: 2025-01-28 17:16:07 浏览: 38
在C#中,你可以通过以下步骤实现这个功能:
```csharp
using System;
using System.Text.RegularExpressions;
public class StringConverter
{
public static string ConvertToCamelCaseWithPrefix(string input)
{
// 首先,去除输入字符串中的下划线并转换为小写
string cleanInput = Regex.Replace(input, "_", "");
// 分割单词,将每个单词的首字母大写
string[] words = cleanInput.Split(' ');
StringBuilder result = new StringBuilder();
foreach (string word in words)
{
if (!string.IsNullOrEmpty(word))
{
result.Append(char.ToUpper(word[0]));
result.Append(word.Substring(1).ToLower());
}
}
// 添加前缀"CddMotor"和后缀"Set"
return "CddMotor" + result.ToString() + "Set";
}
}
```
这个`ConvertToCamelCaseWithPrefix`函数接受一个只包含下划线和大写字母的字符串作为输入。它首先使用正则表达式移除下划线,然后将剩余的部分分割成单词并将首字母大写。最后将结果连接成新的字符串,加上前缀"CddMotor"和后缀"Set"。
使用示例:
```csharp
string input = "motor_wheel Drive_Mode";
string converted = StringConverter.ConvertToCamelCaseWithPrefix(input);
Console.WriteLine(converted); // 输出:"CddMotorMotorWheelDriveModeSet"
```
阅读全文
相关推荐

















