我如何在某个char值处分割字符串,然后获得该分割的最后一个字?

时间:2020-08-28 17:29:41

标签: c# unity3d

这段代码来自我的对话系统,在那部分中,我想在对话字符串太大时拆分对话的字符串,但是我不想在中间分割单词,我想抓住整个单词。

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

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

3 个答案:

答案 0 :(得分:3)

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

<div class="site-header">header</div>
<div class="large-hero__title">hero!</div>

@ Abion47在下面实现了一些建议(也可以寻找标点符号以进行分割,并从行尾处修剪空格):

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

答案 1 :(得分:0)

解决此问题的方法之一是将消息分成单独的单词,然后计算一组单词中的字符数,如果该字符数大于要求的值,则将最后一个单词换行。 / p>

答案 2 :(得分:0)

有几种方法可以做到这一点。就个人而言,我将使用while循环。

var list = new List<string>();
var input = actualInformation.text;

while (input.Length > maxCharDisplayed) 
{
    for (int i = maxCharDisplayed; i >= 0; i--)
    {
        if (!char.IsLetterOrDigit(input[i])) // Or whatever criteria
        {
            list.Add(input.Substring(0, i).TrimEnd());
            input = input.Substring(i).TrimStart();
            break;
        }
    }
            
    // The line is unbreakable at whitespace or punctuation, so break up the word
    list.Add(input.Substring(0, maxCharDisplayed));
    input = input.Substring(maxCharDisplayed);
}

list.Add(input);
相关问题