假设我们有一个长字符串,我们希望将字符串分成64个字符长而不分割单个字:
We prefer questions that can be answered, not just discussed. If your question is about this website, ask it on meta instead.
Run Code Online (Sandbox Code Playgroud)
如果我们这样分裂:
string.SplitByLength(64).ToList();
Run Code Online (Sandbox Code Playgroud)
我们最终会得到两个字符串:
We prefer questions that can be answered, not just discussed. I
f your question is about this website, ask it on meta instead.
Run Code Online (Sandbox Code Playgroud)
分割此字符串的最优雅方式是什么,以便第一个字符串在If字符串开头之前结束If?
换句话说,如何将长字符串拆分成等于或短于所需长度的字符串列表,同时不拆分任何单个字,而是拆分字之间最后可能的空白空间?
您可以给它一个最大值,如64,然后使用它作为索引向后搜索并找到第一个空格并将其拆分.使用递归重复剩余的字符串,你就完成了.
public static IEnumerable<string> SmartSplit(this string input, int maxLength)
{
int i = 0;
while(i + maxLength < input.Length)
{
int index = input.LastIndexOf(' ', i + maxLength);
if(index<=0) //if word length > maxLength.
{
index=maxLength;
}
yield return input.Substring(i, index - i);
i = index + 1;
}
yield return input.Substring(i);
}
Run Code Online (Sandbox Code Playgroud)
var phrase = "We prefer questions that can be answered, not just discussed. If your question is about this website, ask it on meta instead. We prefer questions that can be answered, not just discussed. If your question is about this website, ask it on meta instead.";
var regex = new Regex(@"(.{1,64})(?:\s|$)");
var results = regex.Matches(phrase)
.Cast<Match>()
.Select(m => m.Groups[1].Value)
.ToList();
Run Code Online (Sandbox Code Playgroud)
编辑:我明白了...
| 归档时间: |
|
| 查看次数: |
2705 次 |
| 最近记录: |