110,536
社区成员
发帖
与我相关
我的任务
分享
string s = "123456789";
int i = s.Length;
while (i >= 0) { s = s.Insert(i, "','"); i -= 3; }
s = string.Join("", s.Take(s.Length - 2).Skip(2));
static void Main(string[] args)
{
Console.WriteLine(Slice("123456789"));
Console.WriteLine(Slice("1234567890"));
Console.WriteLine(Slice("1234567890A"));
Console.Read();
}
static string Slice(string info)
{
if (info.Length <= 3)
{
return "'" + info.Substring(0, info.Length) + "'";
}
else
{
return "'" + info.Substring(0, 3) + "'," + Slice(info.Substring(3));
}
}
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
Console.Write(Slice("123456789"));
Console.Write(Slice("1234567890"));
Console.Write(Slice("1234567890A"));
Console.Read();
}
static string Slice(string info)
{
if (info.Length == 0)
{
return string.Empty;
}
else if (info.Length < 3)
{
return "'" + info + "'";
}
else if (info.Length == 3)
{
return "'" + info.Substring(0, 3) + "'";
}
else
{
return "'" + info.Substring(0, 3) + "'," + Slice(info.Substring(3));
}
}
}
}
var s = "123456789";
Console.WriteLine(Regex.Replace(s, ".{3}", m => "'"+m.Value+"',").Trim(','));
public static string ReCombine(this string source,int lenth, char separator = ',',char bracket = '\'')
{
var tmpstr = "";
List<string> result = new List<string>();
var tmplenth = 0;
for (int i = 0; i < source.Length; i++)
{
bool isseparator = tmplenth >= lenth;
if (isseparator)
{
result.Add(bracket + tmpstr + bracket);
tmplenth = 1;
}
else
{
tmplenth++;
}
tmpstr = !isseparator ? tmpstr + source.Substring(i, 1) : source.Substring(i, 1);
if (i==source.Length-1)
{
result.Add(bracket + tmpstr + bracket);
}
}
return string.Join(separator, result);
}
休整了一下不满组长度的时候会丢弃的bug,整理了一下代码,可读性好了一点。
public static string ReCombine(this string source,int lenth, char separator = ',',char bracket = '\'')
{
var tmpstr = "";
List<string> result = new List<string>();
var tmplenth = 0;
for (int i = 0; i < source.Length; i++)
{
if (tmplenth < lenth)
{
tmpstr = tmpstr + source.Substring(i, 1);
tmplenth++;
if (i == source.Length - 1)
{
result.Add(bracket + tmpstr + bracket);
}
}
else
{
result.Add(bracket + tmpstr + bracket);
tmpstr = source.Substring(i, 1);
tmplenth = 1;
}
}
return string.Join(separator, result);
}
然后在你需要重组字符串的时候使用
string aaa = "1234567890123";
var b1b = aaa.ReCombine(3, ',','\'');
我用的是vs2017,net core 2.0+
最低支持我懒得查。