C# 每 N 个字符向字符串添加分隔符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9932096/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Add separator to string at every N characters?
提问by Abdur Rahim
I have a string which contains binary digits. How to separate string after each 8 digit?
我有一个包含二进制数字的字符串。如何在每 8 位数字后分隔字符串?
Suppose the string is:
假设字符串是:
string x = "111111110000000011111111000000001111111100000000";
I want to add a separator like ,(comma) after each 8 character.
我想在每 8 个字符后添加一个分隔符,如 ,(逗号)。
output should be :
输出应该是:
"11111111,00000000,11111111,00000000,11111111,00000000,"
Then I want to send it to a list<> last 8 char 1st then the previous 8 chars(excepting ,) and so on.
然后我想将它发送到 list<> last 8 char 1st 然后是前 8 个字符(除了 ,)等等。
How can I do this?
我怎样才能做到这一点?
采纳答案by Joey
Regex.Replace(myString, ".{8}", "Regex.Split(myString, "(?<=^(.{8})+)");
,");
If you want an array of eight-character strings, then the following is probably easier:
如果你想要一个八字符的字符串数组,那么下面的方法可能更容易:
var s = "111111110000000011111111000000001111111100000000";
var list = Enumerable
.Range(0, s.Length/8)
.Select(i => s.Substring(i*8, 8));
var res = string.Join(",", list);
which will split the string only at points where a multiple of eight characters precede it.
它只会在字符串前面有八个字符的倍数处拆分字符串。
回答by dasblinkenlight
Try this:
尝试这个:
var enumerable = "111111110000000011111111000000001111111100000000".Batch(8).Reverse();
回答by David Peden
If I understand your last requirement correctly (it's not clear to me if you need the intermediate comma-delimited string or not), you could do this:
如果我正确理解了您的最后一个要求(我不清楚您是否需要中间逗号分隔的字符串),您可以这样做:
string data = "111111110000000011111111000000001111111100000000";
const int separateOnLength = 8;
string separated = new string(
data.Select((x,i) => i > 0 && i % separateOnLength == 0 ? new [] { ',', x } : new [] { x })
.SelectMany(x => x)
.ToArray()
);
By utilizing morelinq.
通过使用morelinq。
回答by driis
One way using LINQ:
使用 LINQ 的一种方法:
var str = "111111110000000011111111000000001111111100000000";
# for .NET 4
var res = String.Join(",",Regex.Matches(str, @"\d{8}").Cast<Match>());
# for .NET 3.5
var res = String.Join(",", Regex.Matches(str, @"\d{8}")
.OfType<Match>()
.Select(m => m.Value).ToArray());
回答by Alex
There's another Regex approach:
还有另一种正则表达式方法:
public static List<string> splitter(string in, out string csv)
{
if (in.length % 8 != 0) throw new ArgumentException("in");
var lst = new List<string>(in/8);
for (int i=0; i < in.length / 8; i++) lst.Add(in.Substring(i*8,8));
csv = string.Join(",", lst); //This we want in input order (I believe)
lst.Reverse(); //As we want list in reverse order (I believe)
return lst;
}
回答by Wolf5370
...or old school:
...或老派:
private string InsertStrings(string s, int insertEvery, char insert)
{
char[] ins = s.ToCharArray();
int length = s.Length + (s.Length / insertEvery);
if (ins.Length % insertEvery == 0)
{
length--;
}
var outs = new char[length];
long di = 0;
long si = 0;
while (si < s.Length - insertEvery)
{
Array.Copy(ins, si, outs, di, insertEvery);
si += insertEvery;
di += insertEvery;
outs[di] = insert;
di ++;
}
Array.Copy(ins, si, outs, di, ins.Length - si);
return new string(outs);
}
回答by Johan Larsson
Ugly but less garbage:
丑但垃圾少:
private string InsertStrings(string s, int insertEvery, string insert)
{
char[] ins = s.ToCharArray();
char[] inserts = insert.ToCharArray();
int insertLength = inserts.Length;
int length = s.Length + (s.Length / insertEvery) * insert.Length;
if (ins.Length % insertEvery == 0)
{
length -= insert.Length;
}
var outs = new char[length];
long di = 0;
long si = 0;
while (si < s.Length - insertEvery)
{
Array.Copy(ins, si, outs, di, insertEvery);
si += insertEvery;
di += insertEvery;
Array.Copy(inserts, 0, outs, di, insertLength);
di += insertLength;
}
Array.Copy(ins, si, outs, di, ins.Length - si);
return new string(outs);
}
String overload:
字符串重载:
public string GetString(double valueField)
{
char[] ins = valueField.ToString().ToCharArray();
int length = ins.Length + (ins.Length / 3);
if (ins.Length % 3 == 0)
{
length--;
}
char[] outs = new char[length];
int i = length - 1;
int j = ins.Length - 1;
int k = 0;
do
{
if (k == 3)
{
outs[i--] = ' ';
k = 0;
}
else
{
outs[i--] = ins[j--];
k++;
}
}
while (i >= 0);
return new string(outs);
}
回答by Mateusz Puwa?owski
This is much faster without copying array (this version inserts space every 3 digits but you can adjust it to your needs)
这在不复制数组的情况下要快得多(此版本每 3 位插入一个空格,但您可以根据需要进行调整)
string sep = ",";
int n = 8;
string result = String.Join(sep, x.InSetsOf(n).Select(g => new String(g.ToArray())));
回答by Dusty
A little late to the party, but here's a simplified LINQ expression to break an input string xinto groups of nseparated by another string sep:
聚会有点晚了,但这里有一个简化的 LINQ 表达式,用于将输入字符串x分成n由另一个字符串分隔的组sep:
static string PutLineBreak(string str, int split)
{
for (int a = 1; a <= str.Length; a++)
{
if (a % split == 0)
str = str.Insert(a, "\n");
}
return str;
}
A quick rundown of what's happening here:
快速概述这里发生的事情:
xis being treated as anIEnumberable<char>, which is where theInSetsOfextension method comes in.InSetsOf(n)groups characters into anIEnumerableofIEnumerable-- each entry in the outer grouping contains an inner group ofncharacters.- Inside the
Selectmethod, each group ofncharacters is turned back into a string by using theString()constructor that takes an array ofchars. - The result of
Selectis now anIEnumerable<string>, which is passed intoString.Jointo interleave thesepstring, just like any other example.
x被视为IEnumberable<char>,这就是InSetsOf扩展方法的用武之地。InSetsOf(n)将字符分组到一个IEnumerableofIEnumerable-- 外部分组中的每个条目都包含一个内部n字符组。- 在该
Select方法中,每组n字符通过使用String()带有chars. - 现在的结果
Select是 anIEnumerable<string>,它被传入String.Join以交错sep字符串,就像任何其他示例一样。
回答by GameChanger
I am more than late with my answer but you can use this one:
我的回答迟到了,但你可以使用这个:
##代码##
