regex - Convert Dash-Separated String to camelCase via C# -
i have large xml file contain tag names implement dash-separated naming convention. how can use c# convert tag names camel case naming convention?
the rules are: 1. convert characters lower case 2. capitalize first character after each dash 3. remove dashes
example before conversion
<foo-bar> <a-b-c></a-b-c> </foo-bar> after conversion
<foobar> <abc></abc> </foobar> here's code example works, it's slow process - i'm thinking there better way accomplish goal.
string convertdashtocamelcase(string input) { input = input.tolower(); char[] ca = input.tochararray(); stringbuilder sb = new stringbuilder(); for(int = 0; < ca.length; i++) { if(ca[i] == '-') { string t = ca[i + 1].tostring().toupper(); sb.append(t); i++; } else { sb.append(ca[i].tostring()); } } return sb.tostring(); }
the reason original code slow because you're calling tostring on place unnecessarily. there's no need that. there's no need intermediate array of char. following should faster, , faster version uses string.split, too.
string convertdashtocamelcase(string input) { stringbuilder sb = new stringbuilder(); bool caseflag = false; (int = 0; < 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 claim above fastest possible. in fact, there several obvious optimizations save time. above clean , clear: easy understand.
the key caseflag, use indicate next character copied should set upper case. note don't automatically convert entire string lower case. there's no reason to, since you'll looking @ every character anyway , can appropriate conversion @ time.
the idea here code doesn't more work absolutely has to.
Comments
Post a Comment