首页 > 解决方案 > 我如何以某个 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);
        }

如果有人可以帮助我,我将非常感激!

标签: c#unity3d

解决方案


一种方法是根据最大长度创建一个子字符串,然后找到最后一个空格的索引。如果索引小于零,则没有找到空格,我们只需要切断单词。否则,使用该子字符串,将其从文本中删除,然后继续:

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);

推荐阅读