I’m offering two solutions. The first formats the input as Pascal Case.
static void Main(string[] args)
{
Console.WriteLine(ToCamelCase("camels-drink-LOTS-OF_WATER"));
Console.ReadKey();
}
public static string ToCamelCase(string str)
{
// This holds our output
StringBuilder sb = new StringBuilder();
// Step 1 - split input into array of words
string[] res = str.Split(new char[] { '-', '_' }, System.StringSplitOptions.RemoveEmptyEntries);
// Step 2 - loop through the array
for (int i = 0; i < res.Length; i++)
{
// For each word,
// change all of the letters to lowercase
res[i] = res[i].ToLower();
// Then change the first letter to uppercase
char[] ch = res[i].ToCharArray();
ch[0] = Char.ToUpper(ch[0]);
// Finally, add the result to our output
string c = new string(ch);
sb.Append(c);
}
return sb.ToString();
}
The second formats as Camel Case – it contains additional logic to handle the first word in your input array.
static void Main(string[] args)
{
Console.WriteLine(ToCamelCase("camels-drink-LOTS-OF_WATER"));
Console.ReadKey();
}
public static string ToCamelCase(string str)
{
// This holds our output
StringBuilder sb = new StringBuilder();
// Step 1 - split input into array of words
string[] res = str.Split(new char[] { '-', '_' }, System.StringSplitOptions.RemoveEmptyEntries);
// Step 2 - loop through the array
for (int i = 0; i < res.Length; i++)
{
// For each word,
// change all of the letters to lowercase
res[i] = res[i].ToLower();
// Then change the first letter to uppercase unless it's the first word
char[] ch = res[i].ToCharArray();
if (i != 0)
{
ch[0] = Char.ToUpper(ch[0]);
}
// Finally, add the result to our output
string c = new string(ch);
sb.Append(c);
}
return sb.ToString();
}
Let me know in the comments if you need any more help.
If this answer helps you, please click the gray checkmark to the left. This marks the question as solved and gives me some “rep” which is used to access features on Stack Overflow.
2
solved Index was outside the bounds of the array in my case