0

我正在使用 wxWidgets 框架编写文本编辑器。我需要从文本控件中获取插入符号下的单词。这是我想出的。

static bool IsWordBoundary(wxString& text)
{
    return (text.Cmp(wxT(" "))  == 0 || 
            text.Cmp(wxT('\n')) == 0 ||
            text.Cmp(wxT('\t')) == 0 ||
            text.Cmp(wxT('\r')) == 0);
}

static wxString GetWordUnderCaret(wxTextCtrl* control)
{
    int insertion_point = control->GetInsertionPoint();
    wxTextPos last_position = control->GetLastPosition();
    int start_at, ends_at = 0;

    // Finding starting position: 
    //   from the current caret position, move back each character until 
    //   we hit a word boundary.
    int caret_pos = insertion_point;
    start_at = caret_pos;
    while (caret_pos)
    {        
        wxString text = control->GetRange (caret_pos - 1, caret_pos);
        if (IsWordBoundary (text)) {
            break;
        }

        start_at = --caret_pos;
    }

    // Finding ending position: 
    //   from the current caret position, move forward each character until 
    //   we hit a word boundary.
    caret_pos = ends_at = insertion_point;    
    while (caret_pos < last_position)
    {
        wxString text = control->GetRange (caret_pos, caret_pos + 1);
        if (IsWordBoundary (text)) {
            break;
        }

        ends_at = ++caret_pos;
    }

    return (control->GetRange (start_at, ends_at));
}

此代码按预期工作。但我想知道这是解决问题的最佳方法吗?您是否看到上述代码有任何可能的修复?

任何帮助都会很棒!

4

2 回答 2

1

标点符号是单词的一部分吗?它在您的代码中——这是您想要的吗?

于 2011-04-04T12:56:52.923 回答
0

这是我的做法:

wxString word_boundary_marks = " \n\t\r";
wxString text_in_control     = control->GetValue();
int ends_at                  = text_in_control.find_first_of( word_boundary_marks, insertion_point) - 1;
int start_at                 = text_in_control.Mid(0,insertion_point).find_last_of(word_boundary_marks) + 1;

我没有对此进行测试,因此可能存在一两个“逐一”错误,您应该添加对“未找到”、字符串结尾和任何其他单词标记的检查。我的代码应该为您提供所需的基础。

于 2011-04-04T20:44:38.133 回答