一个由字母组成的字符串,最长14位,要求每隔2位加一个逗号,最左边不加,求一个好的算法例:“abcdefg”    返回“a,bc,de,fg”

解决方案 »

  1.   

    string s = "abcdefg";
    for(int i=s.length-3; i>0; i-=2)
      s.Insert(i, ",");
    试试
      

  2.   


        static String AddSeperators(string input)
        {
            if (string.IsNullOrEmpty(input)) return input;        StringBuilder sb = new StringBuilder();
            sb.Append( input.Substring(0, 2 - input.Length % 2) );
            for (int i = 2 - input.Length % 2; i < input.Length; i += 2)
            {
                sb.AppendFormat(",{0}{1}", input[i], input[i + 1]);
            }
            return sb.ToString();
        }
      

  3.   

                string str = Console.ReadLine();
                char[] arr = str.ToCharArray();
                string newstr = string.Empty;
                for (int i = 0; i < arr.Length; i++)
                {
                    newstr += arr[i].ToString();
                    if ((i + 1) % 2 == 0)
                    {
                        newstr += ",";
                    }
                }
                if (newstr.Substring(newstr.Length - 1, 1) == ",")
                    newstr.Substring(0, newstr.Length - 1);
                Console.WriteLine(str);
                Console.ReadLine();我的方法比较笨 研究insert中
      

  4.   


    string test = "abcdefg";
    string result = System.Text.RegularExpressions.Regex.Replace(yourStr, @"(?<!^)[a-zA-Z]{2}", ",$0", RegexOptions.RightToLeft);如果是用1楼的,需要改下string s = "abcdefg";
    for (int i = s.Length - 2; i > 0; i -= 2)
        s = s.Insert(i, ",");