c# - 将字符串拆分为具有给定长度的子字符串集,由分隔符分隔
问题描述
寻找创建多个子字符串的最佳解决方案,以使每个子字符串的长度不超过参数中的长度值。当包含在子字符串中时,它应该将空格转换为指定的分隔符(让我们以逗号为例)并删除无关的空格。例子:
input string = "Smoking is one of the leading causes of statistics"
length of substring = 7
result = "Smoking,is one,of the,leading,causes,of,statist,ics."
input string = "Let this be a reminder to you all that this organization will not tolerate failure."
length of substring = 30
result = "let this be a reminder to you,all that this organization_will not tolerate failure."
解决方案
我认为,困难的部分是处理空间。这就是我想出的
private string SplitString(string s, int maxLength)
{
string rest = s + " ";
List<string> parts = new List<string>();
while (rest != "")
{
var part = rest.Substring(0, Math.Min(maxLength, rest.Length));
var startOfNextString = Math.Min(maxLength, rest.Length);
var lastSpace = part.LastIndexOf(" ");
if (lastSpace != -1)
{
part = rest.Substring(0, lastSpace);
startOfNextString = lastSpace;
}
parts.Add(part);
rest = rest.Substring(startOfNextString).TrimStart(new Char[] {' '});
}
return String.Join(",", parts);
}
然后你可以这样称呼它
Console.WriteLine(SplitString("Smoking is one of the leading causes of statistics", 7));
Console.WriteLine(SplitString("Let this be a reminder to you all that this organization will not tolerate failure.", 30));
输出是
Smoking,is one,of the,leading,causes,of,statist,ics Let this be a reminder to you,all that this organization,will not tolerate failure.
推荐阅读
- javascript - 在 Android 上的 Web 浏览器中录制 H264
- mysql - 如何在 SQL 查询中将 unix 纪元格式日期转换为 UTC?
- javascript - 使用具有不同域的 javascript 将值从父级传递到 iframe
- c# - 解析 XML 的更简单方法
- angular - 需要有关在 mat-chip-list 上使用所需验证的帮助
- java - 如何在 android/kotlin 中为另一个应用程序的图标添加徽章
- php - 根据数据库中的值更改 div 类值
- flutter - 如何解决渲染 flex 溢出错误的问题?
- c# - 在 SMPP 网关上合并收到的消息部分
- angular - Angular CLI v13 - 无法运行“ng”命令