我想用以下方式拆分一个字符串:
string s = "012345678x0123x01234567890123456789";
s.SplitString("x",10);分拆成
012345678
x0123
x012345678
9012345678
9例如,输入字符串应该在字符"x“或长度10之后拆分--这是第一位的。
以下是我迄今尝试过的:
public static IEnumerable<string> SplitString(this string sInput, string search, int maxlength)
{
int index = Math.Min(sInput.IndexOf(search), maxlength);
int start = 0;
while (index != -1)
{
yield return sInput.Substring(start, index-start);
start = index;
index = Math.Min(sInput.IndexOf(search,start), maxlength);
}
}发布于 2014-06-23 15:25:56
就我个人而言,我不喜欢RegEx。它创建了难以排除错误的代码,并且在您第一次看到它时很难确定它要做什么。因此,对于一个更长的解决方案,我将采用这样的方法。
public static IEnumerable<string> SplitString(this string sInput, char search, int maxlength)
{
var result = new List<string>();
var count = 0;
var lastSplit = 0;
foreach (char c in sInput)
{
if (c == search || count - lastSplit == maxlength)
{
result.Add(sInput.Substring(lastSplit, count - lastSplit));
lastSplit = count;
}
count ++;
}
result.Add(sInput.Substring(lastSplit, count - lastSplit));
return result;
}注意,我将第一个参数更改为char (从字符串中)。这段代码可能会得到更多的优化,但它是好的和可读的,这对我来说更重要。
发布于 2014-06-23 14:23:27
我将使用这个正则表达式:
([^x]{1,10})|(x[^x]{1,9})这意味着:
最多匹配10个不是
x或Matchx的字符,最多匹配9个字符,这些字符不是x
下面是一个工作示例:
string regex = "([^x]{1,10})|(x[^x]{1,9})";
string input = "012345678x0123x01234567890123456789";
var results = Regex.Matches(input, regex)
.Cast<Match>()
.Select(m => m.Value);让你产生价值。
https://stackoverflow.com/questions/24368217
复制相似问题