【问题标题】:How to separate a CString in MFC如何在 MFC 中分隔 CString
【发布时间】:2019-10-19 19:51:06
【问题描述】:

我有一个这样的字符串:DialogTitle = IDD_SETTING_DLG 在一个保存文件中(我已经将它存储在一个名为 m_TextArray 的数组中)。

现在我想获取"IDD_SETTING_DLG" 部分(或至少" IDD_SETTING_DLG")并将其存储在CString 变量中。我使用了Tokenize 方法,但它不起作用。

这是我的代码:

BOOL CTab1::OnInitDialog()
{
    UpdateData();
    ReadSaveFile();
    SetTabDescription();
    UpdateData(FALSE);
    return TRUE;
}

void CTab1::DoDataExchange(CDataExchange* pDX)
{
    CDialog::DoDataExchange(pDX);
    DDX_Text(pDX, IDC_SHOWDES, m_ShowDes);
}

void CTab1::ReadSaveFile()
{
    if (!SaveFile.Open(SFLocation, CFile::modeRead | CFile::shareDenyWrite, &ex))
    {
        ReadSettingFile();
    }
    else
    {
        for (int i = 0; i < 100; i++)
        {
            SaveFile.ReadString(ReadLine);
            m_TextArray[i] = ReadLine.GetString();
        }
    }
}
void CTab1::SetTabDescription() //m_TextArray[2] is where i stored the text
{
    Position = 0;
    Seperator = _T("=");

    m_ShowDes = m_TextArray[2].Tokenize(Seperator, Position);

    while (!m_ShowDes.IsEmpty())
    {
                // get the next token
        m_ShowDes = m_TextArray[2].Tokenize(Seperator, Position);
    }
}

任何解决方案或提示将不胜感激。

【问题讨论】:

  • 在什么情况下它不起作用?请解释一下。
  • @Ian 它没有在IDC_SHOWDES 编辑框上显示任何内容
  • 试试strtok()。查看this 答案:
  • @Ian 你的意思是在while循环结束后调用UpdateData(),还是在循环中调用它?
  • MFC 更喜欢 CString::Tokenize 而不是 C 函数 strtok/strtok_s,后者甚至不兼容 UTF16

标签: c++ mfc


【解决方案1】:

由于您只是在寻找出现在标记之后的字符串部分,因此无需使用Tokenize。只需找到标记字符的位置(您的“=”),然后获取所有内容:

void CTab1::SetTabDescription() //m_TextArray[2] is where i stored the text
{
    CString separator = _T("=");
    CString source = m_TextArray[2];

    // Get position of token...
    int position = source.Find(separator);

    // If token is found...
    if (position > -1 && source.GetLength() > position)
        m_ShowDes = source.Mid(position + 1);  // extract everything after token
}

【讨论】:

    猜你喜欢
    • 2011-12-01
    • 1970-01-01
    • 2011-03-09
    • 2010-11-04
    • 1970-01-01
    • 2014-08-23
    • 1970-01-01
    • 1970-01-01
    • 2011-04-12
    相关资源
    最近更新 更多