在C#中第n次出现特定字符时拆分字符串 [英] Split string at nth occurrence of specific character in C#
问题描述
亲爱的所有人,
我想在特定情况下吐出字符串','
我的字符串是-1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23, 24,25,26,27,28,29,30
i希望将这个字符串分成3个部分,即在第10次出现','后,它应该返回一个string
所以我的第一个字符串是 - 1,2,3,4,5,6,7,8,9,10
和下一个将是 - 11到20等等
但是如果我将字符串拆分为','。它只从字符串中分离出1。
有什么建议吗?
Dear All,
I want to spit string at specific occurrence of ','
My string is- 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30
i want to separate this string in 3 parts i.e. after 10th occurrence of ',', it should return a string
so my first string will be - 1,2,3,4,5,6,7,8,9,10
and next will be - 11 to 20 and so on
but if i split string at ','. it only separate "1" from string.
Any suggestions?
推荐答案
另一种方法。因为尽可能少的内存使用,没有字符串重新分配,没有正则表达式。可以改进吗? :)
Yet another approach. As less memory usage as possible, no string reallocation, no regexp. Could be improved? :)
public IEnumerable<string> SplitBy(string input, char separator, int n)
{
int lastindex = 0;
int curr = 0;
while(curr < input.Length)
{
int count = 0;
while(curr < input.Length && count <n)
{
if(input[curr++] == separator) count++;
}
yield return input.Substring(lastindex,curr-lastindex-(curr < input.Length ? 1 : 0));
lastindex = curr;
}
}
void Main()
{
var inputString = "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30";
foreach(var s in SplitBy(inputString, ',', 10)) Console.WriteLine(s);
}
这是你可以尝试的。
1)拆分字符串,使用String.Split
[ ^ ]。
2)根据事件计数组合数组,例如1到10或11到20等等。
This is what you can try.
1) Split the string on the , usingString.Split
[^].
2) Combine the array based on the occurrence count for e.g. 1 to 10 or 11 to 20 and so on.
此代码基于以前的解决方案和想法,就像有人需要随时可用的一样。 。;)
This code is based on previous solutions and ideas, just if someone needs a "ready-to-use" one... ;)
public static class StringExtensions
{
public static List<string> SplitAtOccurence(this string input, char separator, int occurence)
{
var parts = input.Split(separator);
var partlist = new List<string>();
var result = new List<string>();
for (int i = 0; i < parts.Length; i++)
{
if (partlist.Count == occurence)
{
result.Add(string.Join(separator.ToString(), partlist));
partlist.Clear();
}
partlist.Add(parts[i]);
if (i == parts.Length - 1) result.Add(string.Join(separator.ToString(), partlist)); // if no more parts, add the rest
}
return result;
}
}
用法(在同一名称空间中)是这样的:
The usage (in the same namespace) is something like this:
"1,2,3,4,5,6,7,8,9,10".SplitAtOccurence(',', 4);
这将返回一个List,其中包含以下项目:1,2,3,4, 5,6,7,8和9,10
这篇关于在C#中第n次出现特定字符时拆分字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!