在我的应用程序中,我想向设备发送消息...设备一次只接受14个字符,所以如果我有一个100个字符的字符串意味着我必须每次分割14个字符并发送消息我尝试使用这种方法
string input = "First sentence. Second sentence! Third sentence? Yes.";
string[] sentences = Regex.Split(input, @"(?<=[\.!\?])\s+");
foreach (string sentence in sentences) {
Console.WriteLine(sentence);
}
上面的示例代码按我想要的方式分割句子,但有时会分割超过14个字符
我面临的棘手情况......句子应该低于14个字符,也应该是一个完整的句子
代码应该分开句子,长度应该低于14个字符,任何人都可以帮助我。
答案 0 :(得分:0)
我认为这段代码会做你想要的。为了使它起作用,单词之间必须总是有一个空格来纠正它们。您可能需要根据您的规格进行更改:
string input = "First sentence. Second sentence! Third sentence? Yes.";
string[] sentences = Regex.Split(input, @"(?<=[\.!\?])\s+");
List<string> lines = new List<string>();
string line = "";
foreach (string sentence in sentences)
{
string[] words = sentence.Split(' ');
foreach (string word in words)
{
if (line.Length + word.Length < 14)
line += word + " ";
else
{
lines.Add(line);
line = word+ " ";
}
}
lines.Add(line);
line = "";
}
//Output:
//First
//sentence
//Second
//sentence!
//Third
//sentence?
//Yes