字符串分词器类 (CTokenEx)






4.66/5 (17投票s)
一个非常简单的字符串分词器类。
引言
基本上,我见过其他的字符串分词器,但它们缺乏我所需要的功能。因此,我使用KISS(保持简单,愚蠢)方法为自己创建了一个。这是一个非常简单的示例!!!!
以下是 CTokenEx
类中功能的摘要,您可以
- 使用
SplitPath
将路径分解为各个部分(驱动器/共享名、目录、文件名、扩展名)。它还识别 UNC 名称(而_tsplitpath
不识别)。 - 使用
Join
从CStringArray
创建一个CString
,并使用您选择的分隔符。 - 使用
Split
根据分隔符将CString
分解为CStringArray
。 - 使用
GetString
获取CString
中的第一个子字符串(根据分隔符)。
注意
Split
和 GetString
函数将多个分隔符识别为空字符串,因此它不会将空格添加到数组中(除非您希望这样做)。请参阅下面的示例代码
假设您有一个包含以下内容的 CString
:“abc,def,,,ghi,,jkl,,”
//******************************************************** // Split Function //******************************************************** // // Split will fill an array with: // // NOTE: IF PARAM #4 IS TRUE, YOU'LL SEE LIST #1 ELSE LIST #2 // // LIST #1: // // String Position // ====== ======== // abc 0 // def 1 // 2 // 3 // ghi 4 // 5 // jkl 6 // 7 // 8 // // // LIST #2 (Same String): // // String Position // ====== ======== // abc 0 // def 1 // ghi 2 // jkl 3 // //******************************************************** void <SOME NAME>Dlg::OnSplit() { CTokenEx tok; // CString for the Split Function CString csSplit = "abc,def,,,ghi,,jkl,,"; // CStringArray to fill CStringArray SplitIt; // Call Split tok.Split(csSplit, ",", SplitIt, TRUE); // LIST #1 tok.Split(csSplit, ",", SplitIt, FALSE); // LIST #2 } /******************************************************** // GetString Function //******************************************************** // // GetString will return a string: // // abc // ...and more calls to GetString will return a strings: // def // ghi // jkl // //******************************************************** void <SOME NAME>Dlg::OnGetstring() { CTokenEx tok; char Buf[254]; CString csRef = "abc,def,,,ghi,,jkl,,"; do { // don't return blanks CString csRet = tok.GetString(csRef, ",", FALSE); // return blanks CString csRet = tok.GetString(csRef, ",", TRUE); // Do something with the returned value. } while (!csRef.IsEmpty()); }
我希望其他人觉得这个类有用。