Convert Dash-Separated String to camelCase via C#

前端 未结 5 1648
天涯浪人
天涯浪人 2021-01-21 20:56

I have a large XML file that contain tag names that implement the dash-separated naming convention. How can I use C# to convert the tag names to the camel case naming convention

5条回答
  •  孤独总比滥情好
    2021-01-21 21:18

    The reason your original code was slow is because you're calling ToString all over the place unnecessarily. There's no need for that. There's also no need for the intermediate array of char. The following should be much faster, and faster than the version that uses String.Split, too.

    string ConvertDashToCamelCase(string input)
    {
        StringBuilder sb = new StringBuilder();
        bool caseFlag = false;
        for (int i = 0; i < input.Length; ++i)
        {
            char c = input[i];
            if (c == '-')
            {
                caseFlag = true;
            }
            else if (caseFlag)
            {
                sb.Append(char.ToUpper(c));
                caseFlag = false;
            }
            else
            {
                sb.Append(char.ToLower(c));
            }
        }
        return sb.ToString();
    }
    

    I'm not going to claim that the above is the fastest possible. In fact, there are several obvious optimizations that could save some time. But the above is clean and clear: easy to understand.

    The key is the caseFlag, which you use to indicate that the next character copied should be set to upper case. Also note that I don't automatically convert the entire string to lower case. There's no reason to, since you'll be looking at every character anyway and can do the appropriate conversion at that time.

    The idea here is that the code doesn't do any more work than it absolutely has to.

提交回复
热议问题