c# - 我如何以某个 char 值划分一个字符串,然后得到这个除法的最后一个字?
问题描述
这段代码来自我的对话系统,在那部分我想在字符串太大时分割对话的字符串,但我不想在中间分割单词,我想抓住整个单词。
List<string> a = new List<string>();
if (actualInformation.text.Length > maxCharDisplayed) //Creat Chunks
{
for (int i = 0; i < actualInformation.text.Length; i += maxCharDisplayed)
{
if ((i + maxCharDisplayed) < actualInformation.text.Length)
a.Add(actualInformation.text.Substring(i, maxCharDisplayed));
else
a.Add(actualInformation.text.Substring(i));
}
}else
{
a.Add(actualInformation.text);
}
如果有人可以帮助我,我将非常感激!
解决方案
一种方法是根据最大长度创建一个子字符串,然后找到最后一个空格的索引。如果索引小于零,则没有找到空格,我们只需要切断单词。否则,使用该子字符串,将其从文本中删除,然后继续:
var text = actualInformation.text;
while (text.Length > maxCharDisplayed)
{
// Set cutoff to the last space before max length
var cutoff = text.Substring(0, maxCharDisplayed).LastIndexOf(' ');
// If no space was found, then we have no choice but to use the max length
if (cutoff < 1) cutoff = maxCharDisplayed;
// Add our substring to the list
a.Add(text.Substring(0, cutoff));
// Set our text to now start at the end of the substring we just added
text = text.Substring(cutoff);
}
// Add whatever text is remaining.
a.Add(text);
@Abion47 有一些我在下面实施的建议(也可以寻找要分割的标点符号,并从行尾修剪空白):
var charsToSplitOn = new[]
{' ', '\t', '\r', '\n', '.', ',', ';', ':', '-', ')', '}', '_'};
while (text.Length > maxCharDisplayed)
{
var cutoff = text.Substring(0, maxCharDisplayed - 1)
.LastIndexOfAny(charsToSplitOn) + 1;
if (cutoff < 1) cutoff = maxCharDisplayed;
a.Add(text.Substring(0, cutoff).Trim());
text = text.Substring(cutoff).Trim();
}
if (text.Length > 0) a.Add(text);
推荐阅读
- joomla - JCE 2.5 缺少它的工具栏
- python - 如何在特定位置的 .json 字典中添加新键?
- azure - 安全 Azure 资源免受攻击
- android - 使用 volley 获取位置数据并在 Google 地图中创建多个标记
- powershell - 使用 Powershell 计划任务安装 Windows 安全补丁
- linux - 使用文件中存在的关键字将单个文件拆分并重命名为多个文件
- mqtt - 为什么代理 CPU 的消耗是 0.3,发布者的 qos=2
- flutter - 如何将flutter_web迁移到蜂鸟中颤动?
- reactjs - 为什么在测试中没有调用模拟函数?
- django - 带有千位分隔符的数字时 Django 模板转换错误