- //字符串拆分函数,可以拆分任意长度的字符串
- //字符串可以在任意位置有任意多个空格
- //空格不用区分全角还是半角
- //此函数在BCB 6.0 Enterprise Suite 下测试通过
- //此代码版权归Micheal Ku所有,如用于商业用途须经过作者同意
- void TForm1::subFun(AnsiString str)
- {
- int i=0,j=0;
- strfull =str + " ";
- SQL =""; //使用拆分出来的字符串的变量
- FullShape: //全角空格处理标签
- posfull = strfull.Pos(" ");
- if(strfull.Pos(" ") > 0)
- {
- strfulluse = strfull.SubString(1,posfull-1);
- strfullremain = strfull.SubString(posfull+2,strfull.Length()-posfull-1);
- strfull =strfullremain.Trim();
- strhalf = strfulluse.Trim();
- goto HalfShape;
- }
- else
- if(strfull.Pos(" ") == 0)
- {
- if(strfull != " " && strfull != " " && strfull != "")
- {
- //处理函数
- SQL += "测试字符串'%" + strfull;
- SQL += "', and ";
- }
- goto End;
- }
- HalfShape:
- poshalf = strhalf.Pos(" ");
- if(strhalf.Pos(" ") == 0 )
- {
- if(strhalf != " " && strhalf != " " && strhalf != "")
- {
- //处理函数
- SQL += "测试字符串'%" + + strhalf;
- SQL += "', and ";
- }
- goto FullShape;
- }
- else
- if(strhalf.Pos(" ") > 0)
- {
- strhalfuse = strhalf.SubString(1,poshalf-1);
- strhalfremain =strhalf.SubString(poshalf+1,strhalf.Length()-poshalf);
- strhalf =strhalfremain.Trim();
- //处理函数
- if(strhalfuse != " " && strhalfuse != " "&& strhalfuse != "")
- {
- SQL += "测试字符串'%" + + strhalfuse;
- SQL += "', and ";
- }
- goto HalfShape;
- }
- End:
- SQL += "测试成功";
- ShowMessage(SQL);
- }
- //---------------------------------------------------------------------------
因为笔者编程需要,要用到字符串拆分的功能,类似于搜索引擎查询时输入的一串字符串,不同的关键字以空格隔开,要求把这些关键字拆分开组成一段查询语句。
笔者前期前递归调用算法写了个函数,执行效率极差,后来在网上查找了一下,多数是个拆分已知长度的字符串的例子,字符串的的空格个数非常有限,而且能查找的内容没有一个考虑到半角空格与全角空格以及多个空格同时存在的拆分问题。
没有人能提供个较好的拆分算法及思路,笔者花了四个小时自己写了一个拆分的函数,经测试,完全正确。
笔者使用的编译环境是BCB 6.0,测试完全可正常通过。
使用时不要忘记在头文件中加上函数定义。
头文件中标注下划线的一行为此函数的头文件定义内容。
- //---------------------------------------------------------------------------
- //字符串拆分子函数头文件
- //编译器BCB 6.0 Enterprise Suite
- #ifndef TestH
- #define TestH
- //---------------------------------------------------------------------------
- #include <Classes.hpp>
- #include <Controls.hpp>
- #include <StdCtrls.hpp>
- #include <Forms.hpp>
- //---------------------------------------------------------------------------
- class TForm1 : public TForm
- {
- __published: // IDE-managed Components
- TButton *Button1;
- TEdit *Edit1;
- TButton *Button2;
- TEdit *Edit2;
- void __fastcall Button1Click(TObject *Sender);
- void __fastcall Button2Click(TObject *Sender);
- private: // User declarations
- public: // User declarations
- __fastcall TForm1(TComponent* Owner);
- void subFun(AnsiString str);
- };
- //---------------------------------------------------------------------------
- extern PACKAGE TForm1 *Form1;
- //---------------------------------------------------------------------------
- #endif