C # / WPF: Как найти самые близкие разрывы строк из выделения TextBox - PullRequest
0 голосов
/ 23 октября 2010

У меня есть TextBox txtEditor. Я хочу найти ближайшие разрывы строк и выбрать его

Пример 1: с "без выбора"

предположим, что выделение / курсор *

this is the 1st line of text
this is *the 2nd line of text
this is the 3rd line of text

Я хочу расширить выделение так, чтобы выделение теперь было

this is the 1st line of text
*this is the 2nd line of text*
this is the 3rd line of text

Пример 2: с выбором

this is the 1st line of text
this is *the 2nd line* of text
this is the 3rd line of text

Я хочу расширить выбор так, чтобы выбор был теперь

this is the 1st line of text
*this is the 2nd line of text*
this is the 3rd line of text

Обновление: возможное решение

Я нашел возможное решение, интересно, кто-нибудь нашел лучшее решение?

string tmp = txtEditor.Text;
int selStart = txtEditor.SelectionStart;
int selLength = txtEditor.SelectionLength;
int newSelStart;
int newSelLength;

string tmp1 = tmp.Substring(0, selStart);
if (tmp1.LastIndexOf(Environment.NewLine) < 0)
{
    newSelStart = 0;
}
else
{
    newSelStart = tmp1.LastIndexOf(Environment.NewLine) + Environment.NewLine.Length;
}


tmp1 = tmp.Substring(selStart);
if (tmp1.IndexOf(Environment.NewLine) < 0)
{
    newSelLength = tmp.Length;
}
else
{
    newSelLength = tmp1.IndexOf(Environment.NewLine) + selStart - newSelStart;
}

txtEditor.SelectionStart = newSelStart;
txtEditor.SelectionLength = newSelLength;

1 Ответ

1 голос
/ 23 октября 2010

Ну, в основном проблема в том, что ваш код немного раздутый (и, следовательно, труднее для чтения) и намного менее эффективен, чем должен быть. Производительность, вероятно, не имеет большого значения в вашем случае (эти дублирующие вызовы IndexOf и LastIndexOf меня теряют), но лично я бы переписал ваш код так:

string tmp = txtEditor.Text;
int selStart = txtEditor.SelectionStart;
int selLength = txtEditor.SelectionLength;

int newSelStart = tmp.LastIndexOf(Environment.NewLine, selStart);
if (newSelStart == -1)
    newSelStart = 0;

int newSelEnd = tmp.IndexOf(Environment.NewLine, selStart);
if (newSelEnd == -1)
    newSelEnd = tmp.Length;

txtEditor.SelectionStart = newSelStart;
txtEditor.SelectionLength = newSelEnd - newSelStart;
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...