1

ここで頭脳を少し溶かすと、この問題を解決するためのロジックについての助けが得られる可能性があります。

基本的には、ユーザー入力に基づいて単なるテキストである画像を作成します。

画像の幅は固定されているため、すべてが画像に収まるようにテキストを解析する必要がありますが、空白でのみ分割し、単語を分割しないようにする必要があります。

このような

after X amount of characters split string on last whitespace.
then after the next X amount of characters repeat.

これを行う唯一の方法は、テキストをループして X 文字の前の最後の空白を見つけ (x が空白でない場合)、文字列を分割することです。そして繰り返します。

よりエレガントなソリューションを考えられる人はいますか、それともおそらくこれが最善の方法ですか?

4

1 に答える 1

3

A loop is certainly the way to go. The algorithm you describe should work fine. This can be done quite elegantly using an iterator block. Read more about iterator blocks and the yield return construct here. You could also make the method into an extension method so that it would look something like this:

public static IEnumerable<string> NewSplit(this string @this, int lineLength) {
    var currentString = string.Empty;
    var currentWord = string.Empty;

    foreach(var c in @this)
    {
        if (char.IsWhiteSpace(c))
        {
            if(currentString.Length + currentWord.Length > lineLength)
            {
                yield return currentString;
                currentString = string.Empty;
            }
            currentString += c + currentWord;
            currentWord = string.Empty;
            continue;
        }
        currentWord += c;
    };
    // The loop might have exited without flushing the last string and word
    yield return currentString; 
    yield return currentWord;
}

Then, this can be invoked like the normal Split method:

myString.NewSplit(10);

One of the benefits of iterator blocks is that they allow you to perform logic after an element is returned (the logic right after the yield return statements). This allows the programmer to write the logic the way he or she is probably thinking about the problem.

于 2013-06-15T16:48:31.983 に答える