在我的程序中,如果字符串太长,我需要将它分成多行。现在我正在使用这种方法:
private List<string> SliceString(string stringtocut)
{
List<string> parts = new List<string>();
int i = 0;
do
{
parts.Add(stringtocut.Substring(i, System.Math.Min(18, stringtocut.Substring(i).Length)));
i += 18;
} while (i < stringtocut.Length);
return parts;
}
唯一的问题是,如果第 19 个字符不是空格,我们将一个单词切成两半,看起来很糟糕。
例如
字符串: 这是一个超过 18 个字母的长句子。
Sliced string:
This is a long sent
ance with more than
18 letters.
我如何剪切字符串以使其每节不超过 18 个字符,但如果可以的话返回到最近的空格?我一直在玩弄上面的算法,但我似乎无法理解。
谢谢!
最佳答案
也许使用这样的正则表达式:
var input = "This is a long sentence with more than 18 letters.";
var output = Regex.Split(input, @"(.{1,18})(?:\s|$)")
.Where(x => x.Length > 0)
.ToList();
返回结果:
[ "This is a long", "sentence with more", "than 18 letters." ]
更新
这里有一个处理超长单词的类似解决方案(尽管我感觉它的性能不会那么好,因此您可能需要对其进行基准测试):
var input = "This is a long sentence with a reallyreallyreallyreallyreallyreallyreallyreallyreallyreallyreallyreallyreally long word in it.";
var output = Regex.Split(input, @"(.{1,18})(?:\s|$)|(.{18})")
.Where(x => x.Length > 0)
.ToList();
这会产生结果:
[ "This is a long",
"sentence with a",
"reallyreallyreally",
"reallyreallyreally",
"reallyreallyreally",
"reallyreallyreally",
"really long word",
"in it." ]
关于c# - 在空格处拆分长字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20360497/