本文介绍了帮助字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我想将字符串修改为112233445566在 " 11:22:33:44:55:66" 哪种方法最好? 使用RegExp?如果是的话怎么样? 提前致谢Hi,I want modify a string as "112233445566" in"11:22:33:44:55:66"which is the best method?Using a RegExp? and if yes how?Thanks in advance推荐答案 虽然性能方面很糟糕 - 但实际上并非如此需要 才能在这里使用正则表达式,IMO。这里的代码我相信会比b $ b快得多: if(s.Length!= 12) { //无论你的错误处理是什么 } foreach(char c in s) { if(c<''0''|| c>''9'') { //无论你的错误是什么处理是 } } 返回String.Concat(s.Substring(0,2),":" ;, s.Substring(2,2),":", s.Substring(4,2),":", s.Substring(6,2),":", s.Substring(8,2),":", s.Substring(10,2)); 或者,最后一位: char [] result = new char [17]; int resultIndex = 0; int origIndex = 0; for(int i = 0; i< 6; i ++) { 结果[resultIndex ++] = s [origIndex ++]; 结果[resultIndex ++] = s [origIndex ++]; if(i!= 5) { 结果[resultIndex ++] ='':''; } } 返回新字符串(结果); (这可以避免创建太多额外的字符串。) 我不知道哪个会更快 - 或者使用StringBuilder会更好 - 但是我不认为在这里使用正则表达式是个好主意。 - Jon Skeet - < sk *** @ pobox.com> http://www.pobox.com/~skeet 如果回复小组,请不要给我发邮件That''s terrible in terms of performance though - there''s really no needto use a regex here, IMO. Here''s code which I believe would besignificantly faster:if (s.Length != 12){// Whatever your error handling is}foreach (char c in s){if (c < ''0'' || c > ''9''){// Whatever your error handling is}}return String.Concat(s.Substring(0, 2), ":",s.Substring(2, 2), ":",s.Substring(4, 2), ":",s.Substring(6, 2), ":",s.Substring(8, 2), ":",s.Substring(10, 2));Alternatively, for the last bit:char[] result = new char[17];int resultIndex=0;int origIndex=0;for (int i=0; i < 6; i++){result[resultIndex++]=s[origIndex++];result[resultIndex++]=s[origIndex++];if (i != 5){result[resultIndex++]='':'';}}return new string(result);(That avoids creating too many extra strings.)I don''t know which would be faster - or using a StringBuilder would bebetter - but I don''t think using a Regex here is a good idea.--Jon Skeet - <sk***@pobox.com> http://www.pobox.com/~skeetIf replying to the group, please do not mail me too 这篇关于帮助字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-26 14:58